PHP 8 reference · Array Functions

PHP array_reduce() Function

Reduce an array to a single value by passing a running total and each element to a callback.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
array The input array.
callback fn($carry, $item) returns the new running value.
initial optional The starting value; also returned for an empty array. Default: null

Return value

The final value.

Examples

Total a cartTry it yourself
<?php
$cart = [["price" => 3.5, "qty" => 2], ["price" => 12, "qty" => 1]];
echo array_reduce($cart, fn($sum, $line) => $sum + $line["price"] * $line["qty"], 0), "\n";

Output

19
Group valuesTry it yourself
<?php
$words = ["apple", "avocado", "banana"];
$byLetter = array_reduce($words, function ($groups, $word) {
    $groups[$word[0]][] = $word;
    return $groups;
}, []);
print_r($byLetter);

Output

Array
(
    [a] => Array
        (
            [0] => apple
            [1] => avocado
        )

    [b] => Array
        (
            [0] => banana
        )

)

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?