How to use array_reduce() Function In PHP
The array_reduce() function iteratively reduces the array to a single value using a callback function.
Example: This example shows the use of the above-mentioned appraoch.
<?php
function isAllEqual($arr) {
$val = reset($arr);
return array_reduce($arr,
function($carry, $item) use ($val) {
return $carry && ($item === $val);
}, true);
}
// 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_reduce($array, $callback, $initial) applies the callback to each value, starting with the initial value.
- The callback checks if the current item is equal to the first value.
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