5

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

0

4 Answers 4

10

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');
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the workaround. Here's something a little more creative (but much more expensive I think): $arr = array_diff($arr, array_filter($arr));
Nice. It is also a bit more taxing on the mind to figure out what behaviours are at play here!
7

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?

1 Comment

If filtering out empty values just add !empty($var) as this example is filtering out not empty values, returning an array of empty values.
6

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.

Comments

0

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
)

2 Comments

This is the opposite of the desired effect.
hah, you're absolutely right XD

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.