Check if all elements in Array are equal in PHP

This tutorial will discuss about unique ways to check if all elements in array are equal in php.

Table Of Contents

Method 1: Using array_unique() function

The array_unique() function in PHP accepts an array as an argument, and returns a new array with unique values only. Basically it deletes all the duplicate values from the given array and returns a new array containing unique values only.

To check if all elements in an array are equal, we can pass the array into the array_unique() function. It will return new array with unique value only. If the count of elements in this new array is only one, then it means that all the elements in the original array are equal or same.

Let’s see the complete example,

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

// Get the unique values from the array
$values = array_unique($arr);

// Check if the count of unique values is 1
if (count($values) === 1) {
  echo "Yes, all elements in array are equal";
} else {
  echo "No, All elements in array are not equal";
}
?>

Output

Yes, all elements in array are equal

Method 2: Using array_reduce() function

The array_reduce() function accepts an array and a callback function as arguments. It then applies the given callback function on all elements of the array, to reduce them to a single value, and returns that value.

So to check if all elements in an array are equal, we will pass the array as the first argument into the array_reduce() function and as the second argument we will pass a callback function.

This callback function accepts a boolean value and an element as an argument, and checks if the given element is equal to the first element of array or not. If not, then it will return false, otherwise it will return true.

So the array_reduce() will apply this callback function on all the elements of array.

Basically it will check if all elements of array are equal to the first element of array or not, and reduce the result into single value. If the return value is true, then it means all the elements in array are equal otherwise they are not equal.

Let’s see the complete example,

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

// Check if all elements of array are equal
// to the first element of array
$result = array_reduce(
                    $arr,
                    function($result, $elem) use(&$arr) {
                                return $result && ($elem === $arr[0]);
                    },
                    true);

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

Output

Yes, all elements in array are equal

Summary

We learned about two different ways to check if all elements in an array are equal 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