views:

62

answers:

4

I'm trying to use empty() in array mapping in php. I'm getting errors that it's not a valid callback.

$ cat test.php
<?

$arrays = array(
   'arrEmpty' => array(
        '','',''
    ),
);

foreach ( $arrays as $key => $array ) {

        echo $key . "\n";
        echo array_reduce( $array, "empty" );
        var_dump( array_map("empty", $array) );
        echo "\n\n";

}

$ php test.php
arrEmpty

Warning: array_reduce(): The second argument, 'empty', should be a valid callback in /var/www/authentication_class/test.php on line 12

Warning: array_map(): The first argument, 'empty', should be either NULL or a valid callback in /var/www/authentication_class/test.php on line 13
NULL

Shouldn't this work?

Long story: I'm trying to be (too?) clever and checking that all array values are not empty strings.

+6  A: 

It's because empty is a language construct and not a function. From the manual on empty():

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

Pekka
@Pekka Read my mind +1
Jacob Relkin
You know what I love about this site? That people aren't saying "RTFM!" :D
@user151841 we are not allowed to. That's the only reason ;)
Gordon
A: 

Empty can't be used as a callback, it needs to operate on a variable. From the manual:

Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

Exception e
+2  A: 

Try array_filter with no callback instead:

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

You can then use count(array_filter($array)) to see if it still has values.

Or simply wrap empty into a callable, like this:

array_reduce($array, create_function('$x', 'return empty($x);'));

or as of PHP 5.3

array_reduce($array, function($x) { return empty($x); });
Gordon
Always wondered why there is no boolval() function.
chris
+2  A: 

To add to the others, it's common for PHP developers to create a function like this:

function isEmpty($var)
{
    return empty($var);
}
webbiedave