PHP Reference ยท Array Functions
PHP array_reduce() function
Reference for PHP array_reduce(): fold an array into one value with a carry-over callback, choose an initial value, and avoid common accumulator mistakes.
array_reduce() folds an array into a single value. You supply a callback that receives the result so far (the "carry") and the next element, and returns the new carry. After the last element, the final carry is returned.
The single value can be anything: a number, a string, or even another array, which makes array_reduce() a general-purpose building block for sums, groupings and lookups.
<?php $total = array_reduce([1, 2, 3, 4], fn($carry, $n) => $carry + $n, 0); // 10
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
The callback has this shape:
function (mixed $carry, mixed $item): mixed
| Name | Description |
|---|---|
$array |
The array to fold. |
$callback |
Receives the carry (first call: $initial) and the current element, and returns the next carry. |
$initial |
The starting carry. Defaults to null. |
Return value: the final carry. For an empty array this is $initial unchanged.
Usage notes
- Always give an initial value when the callback does arithmetic or builds an array. With the default
null,$carry + $nworks for numbers, but$carry[...] = ...onnullis a surprise for readers, and an empty input returnsnullinstead of0or[]. - The callback must return the carry. Forgetting
returnmakes the next carrynull. - Keys are not passed to the callback. If you need them, loop with
foreachor reduce overarray_keys(). - Do not modify the carry by reference; return a new value instead. Building an array in a loop with
$carry[] = ...and returning it is fine and is not slow in practice because of copy-on-write. - Common shortcuts exist: use
array_sum()andarray_product()for plain sums and products,max()/min()for extremes, andimplode()for joining strings. - Readability: for complex folds, a plain
foreachloop is often clearer than a long reducer closure. - Type declarations: typing
$carryasarrayorintcatches mistakes when the initial value is forgotten.