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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Alex
  • 66,732
  • 177
  • 439
  • 641

4 Answers4

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');
Treffynnon
  • 21,365
  • 6
  • 65
  • 98
  • 1
    +1 for the workaround. Here's something a little more creative (but much more expensive I think): `$arr = array_diff($arr, array_filter($arr));` – BoltClock Dec 06 '11 at 12:34
  • Nice. It is also a bit more taxing on the mind to figure out what behaviours are at play here! – Treffynnon Dec 06 '11 at 12:38
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?

Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • If filtering out empty values just add !empty($var) as this example is filtering out not empty values, returning an array of empty values. – Faraz Sep 07 '18 at 14:40
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.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
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
)
michael_heath
  • 5,262
  • 2
  • 12
  • 22