Skip to content
PHP Logo

How can PHP developers utilize array_reduce to iteratively reduce an array to a single value using a callback function?

To utilize array_reduce in PHP to iteratively reduce an array to a single value using a callback function, developers can pass an array, a callback function, and an initial value to array_reduce. The callback function should accept two parameters: the current value and the next value in the array, and return a single value that will be used in the next iteration. The initial value is used as the initial value for the reduction.

php
// Example array
$array = [1, 2, 3, 4, 5];

// Callback function to sum the values
$sumCallback = function ($carry, $item) {
    return $carry + $item;
};

// Reduce the array to a single value (sum of all elements)
$result = array_reduce($array, $sumCallback, 0);

echo $result; // Output: 15