Check if all elements in Array are zero in PHP

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

We are going to use the array_reduce() function for this solution.

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 the callback function we will check if the given element is equal to zero or not. It returns true, if the element is zero. Now array_reduce() function will apply this callback function on all the array elements. If all the elements in array are zero, then it will return true. If there is any element that is not zero, then it will return false.

If the array is empty, then it will return the boolean value sent as third argument.

Let’s see the complete example,

<?php
$arr = [0, 0, 0, 0, 0, 0];

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

if ($isAllZero) {
  echo "Yes, all elements in array are zero";
} else {
  echo "No, all elements in array are not zero";
}
?>

Output

Yes, all elements in array are zero

Summary

We learned how to check if all elements of array are zero 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