PHP Array Reduce Function: The Ultimate Guide
The PHP Array Reduce function is a powerful tool for processing arrays and transforming them into a single value. It is often used for tasks such as summing up
array_reduce() walks through an array one element at a time and folds it down to a single value — a sum, a count, the largest item, a rebuilt structure, and so on. On each iteration it passes two things to your callback: the result so far (the accumulator, conventionally named $carry) and the current element ($item). Whatever the callback returns becomes the new accumulator for the next iteration, and the final accumulator is what array_reduce() returns.
Reach for it whenever you need to collapse a whole array into one result and a single array_sum(), array_filter(), or array_map() call is not enough — for example summing only certain elements, building a lookup table, or finding a maximum with custom logic. This guide covers the syntax, how the accumulator flows, common patterns, and the gotchas that trip people up.
Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixed| Parameter | Description |
|---|---|
$array | The input array to fold down. |
$callback | Function called once per element. It receives ($carry, $item) and must return the new accumulator. |
$initial | Optional starting value for $carry. Defaults to null. |
The callback signature is:
function (mixed $carry, mixed $item): mixed$carryholds the result accumulated so far —$initialon the first call.$itemis the current array element.- The return value becomes
$carryfor the next element. Forgetting to return is the most common bug.
array_reduce() ignores the array's keys; only the values are passed to the callback. If you need the keys, loop manually or use array_keys() first.
Common use cases
array_reduce() shines whenever many values must become one. Common patterns include:
- Summing or multiplying elements
- Counting elements that match a condition
- Building an associative array (lookup table) from a list
- Flattening or merging nested arrays
- Finding a minimum or maximum with custom comparison logic
Example 1: Summing up Elements in an Array
The simplest use is adding numbers together. The callback adds the current element to the running total, and the 0 passed as $initial makes the total start at zero.
$carry keeps the running total, starting at 0, and $item is the current number. For a plain sum like this you could also use the built-in array_sum() — array_reduce() becomes useful when the accumulation needs custom logic (sum only even numbers, multiply, etc.).
Example 2: Counting Elements in an Array
You can count elements by incrementing the accumulator on each iteration instead of adding the element's value. Note how $item is intentionally unused here — array_reduce() does not force you to use the current element.
In this example, the $carry variable keeps track of the count, starting at 0. The $item variable holds the current element being processed, but is not used in this case.
Example 3: Building an Associative Array (Lookup Table)
A very practical pattern is turning a list of records into a keyed lookup so you can find an entry by name instead of searching the whole list. The accumulator starts as an empty array and gains one key per record.
<?php
$data = array(
array("name" => "John", "age" => 25),
array("name" => "Jane", "age" => 30),
array("name" => "Jim", "age" => 35)
);
$people = array_reduce($data, function($carry, $item) {
$carry[$item["name"]] = $item["age"];
return $carry;
}, array());
print_r($people);
?>The result is Array ( [John] => 25 [Jane] => 30 [Jim] => 35 ). Each $item is one person record; the callback uses the person's name as the key and their age as the value, returning the updated array so the next iteration can add to it.
Example 4: Flattening Nested Arrays
You can flatten an array of arrays into one flat array by merging each sub-array into the accumulator. Because array_merge() returns a new array, returning its result keeps $carry growing correctly.
Here the input is [[1, 2], [3, 4], [5]]. Each $item is one inner array, and array_merge() appends its values to $carry, producing a single flat list. (This flattens only one level deep.)
Example 5: Merging Several Arrays into One
The same merging idea works for combining a collection of separate arrays. Wrap the arrays you want to join in one outer array and merge each into the accumulator.
$colors and $fruits are merged in order, giving one combined array. With many arrays this is cleaner than chaining several array_merge() calls by hand.
Using arrow functions
Since PHP 7.4 you can write the callback as a concise arrow function. It captures outer variables automatically and implicitly returns its expression, which removes the easy-to-forget return:
<?php
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item, 0);
echo $sum; // 15
?>Common gotchas
- Always return from the callback. If a code path forgets to
return $carry, the accumulator becomesnulland everything after it breaks. Arrow functions sidestep this. - Mind the initial value. With no
$initial,$carrystarts asnull. For numeric sums pass0; for array building pass[]. Otherwise the firstarray_merge(null, …)ornull + 1will misbehave or warn. - Empty arrays return the initial value.
array_reduce([], $fn, 0)returns0; with no initial it returnsnull. Handle that case if an empty input is possible. - Keys are ignored. Only values reach the callback. Reduce over
array_keys($arr)if you need them.
This example finds the maximum without an initial value, treating the first element specially:
<?php
$numbers = [10, 5, 20, 8];
$max = array_reduce($numbers, function ($carry, $item) {
return ($carry === null || $item > $carry) ? $item : $carry;
});
echo $max; // 20
?>Related functions
array_map()— transform every element into a new array (one-to-one), instead of folding to one value.array_filter()— keep only the elements that pass a test.array_sum()— a shortcut for the plain summing case.array_merge()— join arrays directly when no per-element logic is needed.
Conclusion
array_reduce() folds an array into a single value by threading an accumulator through a callback. Once you internalize the ($carry, $item) => newCarry flow, you can sum, count, build lookup tables, flatten, and merge with the same compact tool. Remember the two rules that prevent most bugs: always return the new accumulator, and choose an $initial value that matches the type you are building.