How to use reduce() with Anonymous 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 approach.

PHP
<?php

// Declare an array
$arr = [10, 20, 30, 40, 50];

// Find the largest element using
// array_reduce() function
$largest = array_reduce($arr, function($carry, $item) {
    return ($item > $carry) ? $item : $carry;
});

echo "The Largest Element is: " . $largest;

?>

Output
The Largest Element is: 50

Explanation:

  • $arr is the array containing the elements.
  • array_reduce($arr, function($carry, $item) { return ($item > $carry) ? $item : $carry; }) reduces the array to the largest element using a callback function.


How to Find the Largest Element in an Array in PHP?

Given an array containing some elements, the task is to find the largest element from an array in PHP. PHP provides several ways to achieve this, each with its own advantages and use cases.

Below are the approaches to find the largest element in an array in PHP:

Table of Content

  • Using max() Function
  • Using a Loop
  • Using sort() Function
  • Using reduce() with Anonymous Function

Similar Reads

Using max() Function

The max() function is a built-in PHP function that returns the largest value from an array or a set of values....

Using a Loop

You can use a loop to iterate through the array and find the largest element manually. This approach is more flexible and can be used when additional logic is required....

Using sort() Function

The sort() function sorts the array in ascending order. After sorting, the largest element will be the last element in the array....

Using reduce() with Anonymous Function

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