The array_reduce() function in PHP reduces an array to a single value by iteratively applying a callback function. Each element is processed and combined into one final result.
// Basic syntax of array_reduce()
array_reduce(array $array, callable $callback, mixed $initial = null);
// Reduce array to sum of all numbers
<?php
$numbers = array(1, 2, 3, 4, 5);
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sum;
?>
The callback adds each number to the accumulator, resulting in 15.
// Reduce array to find maximum value
<?php
$numbers = array(1, 2, 3, 4, 5);
$max = array_reduce($numbers, function($carry, $item) {
return ($carry > $item) ? $carry : $item;
});
echo $max;
?>
The accumulator keeps the largest number found so far.
// Combine array elements into a sentence
<?php
$words = array("PHP", "is", "awesome");
$result = array_reduce($words, function($carry, $item) {
return $carry . " " . $item;
});
echo trim($result);
?>
This flow shows how values are accumulated step by step:
// Accumulator flow visualization
Start: carry = 0
1 → carry = 1
2 → carry = 3
3 → carry = 6
4 → carry = 10
5 → carry = 15