Vishesh Joshi
Vishesh Joshi

Reputation: 1611

Is there a way to check if all the elements in an array are null in php

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.

Upvotes: 1

Views: 2927

Answers (5)

flaviovs
flaviovs

Reputation: 597

if ($arr && count(array_filter($arr, 'is_null')) === count($arr)) {
   echo "Array is all NULLs\n";
}

This will call echo only if all elements of $arr are NULLs.

Upvotes: 1

JKirchartz
JKirchartz

Reputation: 18022

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...

Upvotes: -2

zzzzBov
zzzzBov

Reputation: 179086

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.

Upvotes: 1

anubhava
anubhava

Reputation: 785216

Try this:

$nulls = array(null,null,null,null,null,null,null,null);
var_dump(array_unique($nulls) === array(null)); // prints true

Upvotes: 2

pp19dd
pp19dd

Reputation: 3633

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.

Upvotes: 8

Related Questions