What does array_reduce() do?
array_reduce() walks through the array and calls $callback($carry, $item) for each element, where $carry is the value returned by the previous call. The final $carry is returned. It is useful for sums, totals, grouping and building lookup tables.
Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
Parameters
$array- The array to reduce.$callback- Functionfn($carry, $item)returning the new carry value. It does not receive keys.$initial- Starting value of$carry. Defaults tonull; it is also the return value for an empty array.
Return value
The final carry value, or $initial if the array is empty.
array_reduce() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Sum and product
<?php
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
$product = array_reduce($numbers, fn($carry, $n) => $carry * $n, 1);
echo "Sum: $sum\n";
echo "Product: $product\n";
Output:
Sum: 15 Product: 120
2. Shopping cart total
<?php
$cart = [
["item" => "Book", "price" => 12.50, "qty" => 2],
["item" => "Pen", "price" => 1.25, "qty" => 4],
];
$total = array_reduce($cart, fn($sum, $line) => $sum + $line["price"] * $line["qty"], 0);
echo "Total: " . number_format($total, 2) . "\n";
Output:
Total: 30.00
3. Group rows by a field
<?php
$people = [
["name" => "Ann", "team" => "red"],
["name" => "Ben", "team" => "blue"],
["name" => "Cara", "team" => "red"],
];
$byTeam = array_reduce($people, function ($groups, $person) {
$groups[$person["team"]][] = $person["name"];
return $groups;
}, []);
print_r($byTeam);
Output:
Array
(
[red] => Array
(
[0] => Ann
[1] => Cara
)
[blue] => Array
(
[0] => Ben
)
)
4. Why you should pass an initial value
<?php
var_dump(array_reduce([], fn($c, $n) => $c + $n));
var_dump(array_reduce([], fn($c, $n) => $c + $n, 0));
Output:
NULL int(0)
Common mistakes and gotchas
- Missing initial value: without it the first carry is
nulland an empty array returnsnull. - Forgetting to return: a multi-line closure must
return $carry;, otherwise the next call receivesnull. - Simple sums:
array_sum()andarray_product()are shorter and faster for plain numbers.