Is there a way to check if all the elements in an array are null in PHP?
For instance, I have an array array(null,null,null,null)
- is there a way to check this scenario?
I am looking for a better way than just looping through the entire array and checking each element.
array_unique()
is O(n) in the best case, whereas a simple loop (and break) as @halfer suggests is O(n) only in the worst case. That means if you have a million items and the second item is not null, with array_unique()
you'll still end up checking the remaining 999,998 items (not to mention potentially using quite a lot of memory) even though you already have your answer. Don't do this - Jordan Running 2012-04-03 20:26
Another simple way of making this work is to use the max()
function.
max(array( 3, 4, null, null ) ) # is 4
max(array( null, null, null, null) # is null
Thus you can issue a simple if( is_null(max($array)) ) { ... }
call.
Try this:
$nulls = array(null,null,null,null,null,null,null,null);
var_dump(array_unique($nulls) === array(null)); // prints true
array_filter
would work:
function checkIsset($val) {
return isset($val);
}
$arr = array(null, null, null, ..., null);
$filteredArr = array_filter($arr, 'checkIsset');
if (count($filteredArr)) {
//not all null
} else {
//all null
}
or if (empty($filteredArr))
if you want the inverse.
isset
as callback - PeeHaa 2012-04-03 19:55
You can use array_filter()
like this:
$nulls = array(null,null,null,null,null);
if(count(array_filter($nulls)) == 0){
echo "all null (or false)";
}
Dunno what you expect in this array, but this lumps false in with the nulls...
count($removenulls) == 0
Aaron W. 2012-04-03 19:49
array(0, '', null, array());
this would fail. array_filter
simply checks for falsey values, not null
values - zzzzBov 2012-04-03 19:52
foreach
and test each element - halfer 2012-04-03 19:44