Question

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?

Was it helpful?

Solution

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

OR

array_reduce($myarray,
             function($result,$value) {
                 return $result && is_null($value);
             },
             TRUE
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top