empty() not a valid callback?

2019-07-07 05:08发布

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.

5条回答
Root(大扎)
2楼-- · 2019-07-07 05:44

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); });
查看更多
Lonely孤独者°
3楼-- · 2019-07-07 05:45

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

查看更多
聊天终结者
4楼-- · 2019-07-07 06:02

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

function isEmpty($var)
{
    return empty($var);
}
查看更多
霸刀☆藐视天下
5楼-- · 2019-07-07 06:05

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;

}
查看更多
淡お忘
6楼-- · 2019-07-07 06:07

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)).

查看更多
登录 后发表回答