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.
Try
array_filter
with no callback instead:You can then use
count(array_filter($array))
to see if it still has values.Or simply wrap empty into a callable, like this:
or as of PHP 5.3
It's because
empty
is a language construct and not a function. From the manual on empty():To add to the others, it's common for PHP developers to create a function like this:
I don't know why, somehow empty() worked for me inside a callback.
The reason why I was originally getting this error was because I was trying to callback as an independent function, whereas it was inside my class and I had to call it using array(&$this ,'func_name')
See code below. It works for me. I am php 5.2.8, if that matters...
Empty can't be used as a callback, it needs to operate on a variable. From the manual: