Codectionary / Developer documentation / PHP

PHP array_reduce accumulators

array_reduce combines array values into a single result by passing an accumulator and the next element to a callback. An explicit initial value makes empty input predictable.

Syntax

array_reduce($items, $callback, $initial)

Examples

PHP array_reduce accumulators

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$cart = [['price' => 4, 'quantity' => 2], ['price' => 3, 'quantity' => 1]];
$total = array_reduce($cart, fn(int $sum, array $row): int =>
    $sum + $row['price'] * $row['quantity'], 0);
echo $total, PHP_EOL;
  1. Output: 11. The accumulator starts at zero; each row adds its extended price.

Best practices

  • Always specify the initial value and keep the callback focused. Use integer minor units for exact monetary totals.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading