user1676521
user1676521

Reputation:

PHP function to determine is all elements in an array are null

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:

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?

Upvotes: 1

Views: 104

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

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

OR

array_reduce($myarray,
             function($result,$value) {
                 return $result && is_null($value);
             },
             TRUE
);

Upvotes: 4

Related Questions