Skip to content
Tutorials Center
My learning

Topics

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
<?php
$total = array_reduce([1, 2, 3, 4], fn($carry, $n) => $carry + $n, 0);
// 10

Try it

PHP Sums, products and strings

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.

PHP Building arrays: grouping and counting

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

PHP
array_reduce(array $array, callable $callback, mixed $initial = null): mixed

The callback has this shape:

PHP
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 + $n works for numbers, but $carry[...] = ... on null is a surprise for readers, and an empty input returns null instead of 0 or [].
  • The callback must return the carry. Forgetting return makes the next carry null.
  • Keys are not passed to the callback. If you need them, loop with foreach or reduce over array_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() and array_product() for plain sums and products, max()/min() for extremes, and implode() for joining strings.
  • Readability: for complex folds, a plain foreach loop is often clearer than a long reducer closure.
  • Type declarations: typing $carry as array or int catches mistakes when the initial value is forgotten.