Check if all elements in Array are true in PHP

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

To check if all elements in an array are true, we can use the array_reduce() function. It accepts an array and a callback function as arguments, and applies the given callback function on all the elements of the array, to reduce them to single value.

So, to check if all elements in array are true, we will pass the array as the first argument to the array_reduce() function, and as the second argument we will pass a callback function. Which accepts a boolean value and an element as argument, and returns true if the given element is true, otherwise it returns false.

So, if any element in the array is false then the array_reduce() will return the value false. Whereas if all the elements of the array are true, then it will return true.

Let’s see the complete example,

<?php
$arr = array(true, true, true, true, true);

// Check if all elements of an array are true
$result = array_reduce(
                    $arr,
                    function($result, $element) {
                          return $result && $element;
                    },
                    true);

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

Output

Yes, all elements in array are true

Summary

We learned how to check if all values in an array evaluates to true in PHP. Thanks.

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