How to use array_filter() Function In PHP

The array_filter() function filters elements of an array using a callback function. If all elements pass the filter (i.e., are equal to the first element), the filtered array will have the same number of elements as the original array.

Example: This example shows the use of the above-mentioned appraoch.

PHP
<?php

function isAllEqual($arr) {
    $val = reset($arr);
    
    return count(array_filter($arr, 
        function($item) use ($val) {
            return $item === $val;
        })) === count($arr);
}

// Driver code
$arr1 = [1, 1, 1, 1];
$arr2 = [4, 2, 3, 4];

echo isAllEqual($arr1) 
    ? "All values are equal\n" 
    : "Values are not equal\n";

echo isAllEqual($arr2) 
    ? "All values are equal." 
    : "Values are not equal.";

?>

Output
All values are equal
Values are not equal.

Explanation:

  • reset($array) gets the first value of the array.
  • array_filter($array, $callback) returns an array of elements that pass the filter.
  • The callback checks if each element is equal to the first value.
  • The filtered array should have the same length as the original if all elements are equal.

How to Check all values of an array are equal or not in PHP?

Given an array with some elements, the task is to check whether all values of array elements are equal or not.

Below are the approaches to check if all values of an array are equal or not in PHP:

Table of Content

  • Using array_unique() Function
  • Using array_reduce() Function
  • Using array_filter() Function
  • Using a Loop

Similar Reads

Using array_unique() Function

The array_unique() function removes duplicate values from an array. If all values in the array are equal, the resulting array after applying array_unique() will have only one element....

Using array_reduce() Function

The array_reduce() function iteratively reduces the array to a single value using a callback function....

Using array_filter() Function

The array_filter() function filters elements of an array using a callback function. If all elements pass the filter (i.e., are equal to the first element), the filtered array will have the same number of elements as the original array....

Using a Loop

A simple loop can iterate through the array to check if all values are equal....