Reputation: 18046
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.
Upvotes: 3
Views: 3162
Reputation: 194
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...
$table_values = array_filter( $table_values, array(&$this, 'remove_blank_rows') );
function remove_blank_rows($row){
$not_blank = false;
foreach($row as $col){
$cell_value = trim($col);
if(!empty( $cell_value )) {
$not_blank = true;
break;
}
}
return $not_blank;
}
Upvotes: 0
Reputation: 316969
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); });
Upvotes: 7
Reputation: 48897
To add to the others, it's common for PHP developers to create a function like this:
function isEmpty($var)
{
return empty($var);
}
Upvotes: 2
Reputation: 1874
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)).
Upvotes: 0
Reputation: 449415
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
Upvotes: 9