phparrays

Determine if all the values in a PHP array are null


I'm looking for the most performance friendly approach to check if all values in an array are null or if it at least has one element with other types.

i.e. i need a method called containsOnlyNull($array), which returns booleans according to the passed array

e.g. :

$a = containsOnlyNull([null,null,null,null,null]);
$b = containsOnlyNull([null,null,1,null,null]);

// $a will be true
// $b will be false

Solution

  • function containsOnlyNull($input)
    {
        return empty(array_filter($input, function ($a) { return $a !== null;}));
    }