Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if all the values in a PHP array are null

Tags:

arrays

php

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
like image 726
Ali Avatar asked Jun 15 '15 11:06

Ali


People also ask

How do you check if all elements in an array are null?

To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to null .

Is array null in PHP?

An array cannot be null. If it's null, then it is not an array: it is null.

How check value is null or not in PHP?

To check a variable is null or not, we use is_null() function. A variable is considered to be NULL if it does not store any value. It returns TRUE if value of variable $var is NULL, otherwise, returns FALSE.


1 Answers

function containsOnlyNull($input)
{
    return empty(array_filter($input, function ($a) { return $a !== null;}));
}
like image 175
Mantas Avatar answered Sep 16 '22 15:09

Mantas