Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array_filter and empty()

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();

like image 964
Alex Avatar asked Nov 29 '22 03:11

Alex


1 Answers

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');
like image 139
Treffynnon Avatar answered Dec 18 '22 21:12

Treffynnon