简体   繁体   中英

What is the best way to check if array has values other than null in php?

In PHP empty([null, null, null]) will obviously return false .

What is the best way from the performance point of view to detect that an array contains only null values?

Performance testing of the answers so far using this code, first with an array of 1000 null values, then an array with 999 null values and one (random) non-null value:

$array = array_fill(0, 1000, null);
$elapsed = array();
foreach (array('Nick1', 'Nick2', 'Eddie', 'Vivek') as $func) {
    $start = explode(' ', microtime());
    for ($i = 0; $i < 10000; $i++) $func($array);
    $elapsed[$func] = elapsed_time($start);
}

In the tables, Nick1 = array_reduce , Nick2 = count(array_filter) , Vivek = for (aka Nick3).

Results (all null array):

Function    Elapsed Time    Delta
Vivek       0.654           0%
Nick2       0.886           35%
Nick1       0.964           47%
Eddie       3.122           377%

Results (array with 999 null values, 1 random non-null value, different each iteration)

Function    Elapsed Time    Delta
Vivek       0.305           0%
Nick2       0.888           191%
Nick1       0.891           192%
Eddie       3.114           921%

As can be seen for the all- null array, the for loop is considerably faster, mainly because it doesn't suffer the overhead of a function call for each value. For the array with one non- null value, it's even faster as it can break as soon as it finds a non- null value.

Leave a comment if you want your answer to be added to the test...

One option is using array_unique to get all unique array values. If there is only one element and that element is null, all elements are null.

$unique = array_unique( [null, null, null] );

if ( count( $unique ) === 1 && $unique[0] === null ) {
    //All Null
} else {
    //Not all Null
}

Here's a couple of ways to determine that an array only contains null values:

$array = array(null, null, null);
echo array_reduce($array, function ($c, $v) { return $c && is_null($v); }, true) ? 'empty' : 'not empty';
echo !count(array_filter($array, function($v) { return !is_null($v); })) ? 'empty' : 'not empty';

Output:

empty
empty

And then of course we have the humble for loop:

$c = count($array);
for ($i = 0; $i < $c; $i++) {
    if (!is_null($array[$i])) {
        echo "not empty";
        break;
    }
}
if ($i == $c) echo "empty";

Demo on 3v4l.org

$arrayIsNull = ($array = array_unique([null, null, null])) && (next($array) === false && is_null($array[0]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM