1

I want to know if there is a built-in, or better method to test if all elements of an array are null.

Here is my (working) solution:

<?php
    function cr_isnull($data_array){    
        foreach($data_array as $value){ 
            if(!is_null($value)){return false;}
        }
    return true;
    }
?>

Explanation:

  • If the function finds ANY value in the array that is not null it returns false, otherwise after "looping" through all of the array elements it returns true.

I cant use empty() because my definition of empty does not fit PHP's definition.

Any thoughts, or am I good to go with what I have?

1 Answer 1

4
count(array_filter($myarray,'is_null')) == count($myarray);

OR

array_reduce($myarray,
             function($result,$value) {
                 return $result && is_null($value);
             },
             TRUE
);
Sign up to request clarification or add additional context in comments.

5 Comments

Probably don't need the second count(), OP just wants to see if all values are null or not.
@nickb - so how would it test that the filter was returning all the original values or not without the count? Using an array_reduce() could eliminate the need for a count() though
If it's an array of all null values, array_filter() will return an array with zero elements. Compare it to 0, if it's true, the original array had all nulls, if not, it didn't.
@nickb - If the callback function returns true (is_null will return TRUE if a value is NULL), the current value from input is returned into the result array.... meaning that the returned array will have all its original elements if they were all NULL values. Alternatively, you could create a callback that would use !is_null() to return an empty array if all the array entries were NULL values
A slight variation of this worked great for my application. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.