使用带有回调函数的array_filter删除空数组元素
I'm trying to delete empty elements in an array with the function array_filter.
When i use an external callback like this :
function callback($a) { return !empty($a);}
$arr = array("abc",'','ghi');
$res = array_filter($arr, "callback");
it works as expected.
But if i use array_filter like that :
$arr = array("abc",'','ghi');
$res = array_filter($arr, function($a) { return !empty($a);});
It fails with the error :
PHP Parse error: syntax error, unexpected T_FUNCTION in test.php on line 2
What am i doing wrong ?
我正在尝试使用函数array_filter删除数组中的空元素。 p>
当我使用这样的外部回调时: p>
函数回调($ a){return!empty($ a);}
$ arr = array(“ abc“,'','ghi');
$ res = array_filter($ arr,”callback“);
code> pre>
它按预期工作。 p>
但如果我像这样使用array_filter: p>
$ arr = array(“abc”,'','ghi');
$ res = array_filter($ arr,function($ a){return!empty($ a);});
code> pre>
它失败并显示错误: p>
PHP解析错误:语法错误,第2行test.php中的意外T_FUNCTION
code> pre>
我做错了什么 ? p>
div>
It seems that you’re using a PHP version that does not support anonymous functions (available since PHP 5.3.0).
But array_filter
does already filter empty values if you don’t specify a callback function:
If no
callback
is supplied, all entries ofinput
equal to FALSE (see converting to boolean) will be removed.
It works well with PHP5. Check your PHP version, and upgrade if necessary.