Array_filter and empty()

2020-02-12 21:37发布

问题:

Warning: array_filter() expects parameter 2 to be a valid callback, function 'empty' not found or invalid function name....

Why is empty considered a invalid callback?

$arr = array_filter($arr, 'empty');

This works: if(empty($arr['foo'])) die();

回答1:

Answer

empty() is not a function but a language construct and array_filter() can only accept a function as its callback.

This is given as a small note on the manual page:

Note: Because this is a language construct and not a function, it cannot be called using variable functions

Work around

To work around this you can wrap empty in another function for example:

function empty_test($val) {
    return empty($val);
}

And then call it like so:

$arr = array_filter($arr, 'empty_test');


回答2:

empty() is a language construct, and not a true function in terms of PHP, so you can't pass its name as an argument to functions like array_filter() and call_user_func_array().

From the manual:

Note: Because this is a language construct and not a function, it cannot be called using variable functions

For a workaround, just wrap it in another user-defined function; see Treffynnon's answer.



回答3:

See the documentation page on empty():

Note: Because this is a language construct and not a function, it cannot be called using variable functions

So basically empty() is not a function, and because callback must be a function, empty() can not be passed as callback.

But you can create callback that may use empty(). The following should work in PHP > 5.3:

$arr = array_filter($arr, function($var){
    return empty($var);
});

In PHP < 5.3 you will need to create similar function first and then pass it to the array_filter().

Did it help?



回答4:

You can use just array_filter() function without callback:

Remove empty array elements in PHP

$arr = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0);
print_r(array_filter($arr)); // removing blank, null, false, 0 (zero) values

Result:

Array
(
    [0] => PHP
    [1] => HTML
    [2] => CSS
    [4] => JavaScript
)