Check if All elements in Array are null in PHP

This tutorial will discuss about a unique way to check if all elements in array are null.

We can use the array_reduce() function to get the work done here.

The array_reduce() function accepts three arguments,

  1. An array
  2. A callback function.
  3. A boolean value. It will be returned if the array is empty.

It then applies the given callback function on all the elements of array, and reduce them to a single value.

The callbcak accepts two argument. First argument is the cumalative result value, which was returned by the previous call to this function. Second argument is the array the element. Inside this callback function, we will check if a element passed as second argument is null or not. If it is null, then return true, otherwise it returns false. Also, if the first argument is false, then it will always return false only, without checking the value of second element.

In the end, the array_reduce() function returns true, if all the elements in array are null.

Let’s see the complete example,


// Example usage
$arr = [null, null, null, null, null, null];

// Check if all elements in the array are null
$isAllNull = array_reduce($arr,
                          function($result, $elem) {
                              return $result && ($elem === null);
                          }, true);

if ($isAllNull) {
  echo "Yes, all elements in array are null";
} else {
  echo "No, all elements in array are not null";


Yes, all elements in array are null


We learned how to check if all elements of array are null in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top