简体   繁体   English

PHP:语法错误帮助;

[英]PHP: syntax error help expected ;

Can someone help me figure out why I'm getting a syntax error with this function: 有人可以帮我弄清楚为什么我使用此函数遇到语法错误:

function removeFromArray(&$array, $key){
        foreach($array as $j=>$i){
            if($i == $key){
                $array = array_values(unset($array[$j])); //error on this line says expected ;
                return true;
                break;
            }
        }
}

Any help most appreciated! 任何帮助,不胜感激!

Jonesy 琼斯

Remove array_values . 删除array_values It seems you just want to remove one value and unset is already doing the job: 看来您只想删除一个值,而unset已经完成了这项工作:

function removeFromArray(&$array, $key){
    foreach($array as $j=>$i){
        if($i == $key){
            unset($array[$j]);
            return true;
        }
    }
}

More about unset . 有关未unset更多信息

Demo 演示版


Side note: 边注:

  • The code after a return is not executed anymore, so break is unnecessary. return后的代码不再执行,因此不需要break
  • $key is a misleading variable name here. $key是一个误导性的变量名。 Better would be $value . 最好是$value

Update: If you want to reindex the values of the array (in case you have a numeric array), you have to do it in two steps (as unset does not return a value): 更新:如果要为数组的值重新索引 (如果您有数字数组),则必须分两步执行(因为未unset不会返回值):

unset($array[$j]);
$array = array_values($array);

Demo 演示版

You're trying to use the unset function inside array_values? 您正在尝试在array_values中使用unset函数吗? What exactly are you expecting to happen here? 您究竟希望在这里发生什么?

You should be able to just use: unset($array[$j]); 您应该可以使用:unset($ array [$ j]);

As you've passed the array in by reference, this should be sufficient to remove it. 在通过引用传递数组时,这足以删除它。 No need to play with array values. 无需使用数组值。

The problem is the unset. 问题是尚未解决。 array_values expect an array as parameter, but unset does not have any return value. array_values期望将数组作为参数,但是unset没有任何返回值。

I see what you're trying to do, I suggest you use this instead: 我了解您要执行的操作,建议您改用以下方法:

function removeFromArray(&$array, $key){
        foreach($array as $j=>$i){
            if($i == $key){
                unset($array[$j]);
            }
        }
}

You don't actually need to return anything. 您实际上不需要返回任何东西。 unset is a void function. unset是一个无效函数。

取消设置不会返回任何内容:

void unset ( mixed $var [, mixed $var [, mixed $... ]] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM