This question already has an answer here:
Works: returns [false,null]
array_filter([1, 2, 3, false, null], function($value) {
return empty($value);
});
Does not Work:
array_filter([1, 2, 3, false, null], empty); // syntax error, unexpected ')',expecting '('
Why cant i just pass in the function as an argument?
</div>
empty() is not a function, it's a language construct. array_filter expects a callable as the second argument. You will need to use a wrapper function exactly as you have in your first example:
array_filter([1, 2, 3, false, null], function($value) {
return empty($value);
});
What is empty meant to be in your second example?
Note that php's "empty" is not a function, but a language construct. Therefore you cannot use it as a function. That is explained in the documentation: http://php.net/manual/en/function.empty.php (Scroll down to the "Notes" section...)
That explains why the first variant does work, whilst the second results in a syntax error.
Functions can be passed into any function/method that takes a callable
argument. However, empty (), in spite of how it's written in code, is not a function. It's a language construct.
If you want to pass empty as a callable, you have no choice but to wrap it in a user-defined function.
$func = function ($param) { return empty ($param); };
print_r (array_filter ([1,2, NULL, 3, 4, FALSE, 5, 6, 0, "", 7, 8, 9], $func));
or
print_r array_filter (([1,2, NULL, 3, 4, FALSE, 5, 6, 0, "", 7, 8, 9], function ($param) {
return empty ($param);
}));
Other language constructs are affected as well, so you might want to consult the manual for a list of language constructs (all the ones that terminate with () like functions are things you can't use with functions that take a callable argument).