Empty () invalid callback?

I am trying to use empty () in array mapping in php. I get errors that this is 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

Doesn't that work?

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

+3
source share
5 answers

This is because it emptyis a language construct, not a function. From the manual on the empty ():

Note. Since this is a language construct, not a function, it cannot be called using variable functions

+9
source

Try array_filterinstead of the callback:

, , FALSE (. ), .

count(array_filter($array)), , .

, :

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

PHP 5.3

array_reduce($array, function($x) { return empty($x); });
+7

, PHP ​​:

function isEmpty($var)
{
    return empty($var);
}
+2

, . manual:

: empty() , . , : empty (trim ($ name)).

0

, , - () .

The reason I initially got this error was because I tried to call the feedback as an independent function, while it was inside my class, and I had to call it using an 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;

}
0
source

Source: https://habr.com/ru/post/1740374/


All Articles