array_reduce() goes through an array and combines all items into one value: a sum, a total, a string, even a new array.
<?php
$prices = [100, 250, 50];
$total = array_reduce($prices, fn($carry, $price) => $carry + $price, 0);
echo $total;
400
How it works
The function receives two values:
$carry: the result so far (it starts as the third argument, here0).$item: the current item.
Whatever the function returns becomes the next $carry.
| Round | $carry | $item | Returns |
|---|---|---|---|
| 1 | 0 | 100 | 100 |
| 2 | 100 | 250 | 350 |
| 3 | 350 | 50 | 400 |
Always give the starting value
Without the third argument, the starting value is null, which can cause surprises (for example, on an empty array).
<?php
var_dump(array_reduce([], fn($c, $i) => $c + $i));
var_dump(array_reduce([], fn($c, $i) => $c + $i, 0));
NULL
int(0)
A shopping cart total
<?php
$cart = [
["name" => "Pen", "price" => 12, "qty" => 5],
["name" => "Book", "price" => 250, "qty" => 2],
];
$total = array_reduce($cart, fn($sum, $line) => $sum + $line["price"] * $line["qty"], 0);
echo $total;
560
Find the longest word
<?php
$words = ["php", "javascript", "css"];
$longest = array_reduce($words, fn($best, $word) => strlen($word) > strlen($best) ? $word : $best, "");
echo $longest;
javascript
Build an array: group by a field
<?php
$people = [
["name" => "Ana", "city" => "Pune"],
["name" => "Ben", "city" => "Delhi"],
["name" => "Cy", "city" => "Pune"],
];
$byCity = array_reduce($people, function (array $groups, array $person): array {
$groups[$person["city"]][] = $person["name"];
return $groups;
}, []);
print_r($byCity);
Array
(
[Pune] => Array
(
[0] => Ana
[1] => Cy
)
[Delhi] => Array
(
[0] => Ben
)
)
When a loop is clearer
array_reduce() is neat for small totals. For anything with several steps, a foreach is easier to read.
<?php
$prices = [100, 250, 50];
$total = 0;
foreach ($prices as $price) {
$total += $price;
}
echo $total;
400
For plain sums, array_sum() is the shortest. Use array_reduce() when the combining rule is your own.