Skip to content

PHP Tutorial Arrays

Reducing Arrays

Lesson 127 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

array_reduce() goes through an array and combines all items into one value: a sum, a total, a string, even a new array.

index.php
PHP
<?php
$prices = [100, 250, 50];

$total = array_reduce($prices, fn($carry, $price) => $carry + $price, 0);

echo $total;
Output
OUTPUT
400

How it works

The function receives two values:

  • $carry: the result so far (it starts as the third argument, here 0).
  • $item: the current item.

Whatever the function returns becomes the next $carry.

Round$carry$itemReturns
10100100
2100250350
335050400

Always give the starting value

Without the third argument, the starting value is null, which can cause surprises (for example, on an empty array).

index.php
PHP
<?php
var_dump(array_reduce([], fn($c, $i) => $c + $i));
var_dump(array_reduce([], fn($c, $i) => $c + $i, 0));
Output
OUTPUT
NULL
int(0)

A shopping cart total

index.php
PHP
<?php
$cart = [
    ["name" => "Pen", "price" => 12, "qty" => 5],
    ["name" => "Book", "price" => 250, "qty" => 2],
];

$total = array_reduce($cart, fn($sum, $line) => $sum + $line["price"] * $line["qty"], 0);

echo $total;
Output
OUTPUT
560

Find the longest word

index.php
PHP
<?php
$words = ["php", "javascript", "css"];

$longest = array_reduce($words, fn($best, $word) => strlen($word) > strlen($best) ? $word : $best, "");

echo $longest;
Output
OUTPUT
javascript

Build an array: group by a field

index.php
PHP
<?php
$people = [
    ["name" => "Ana", "city" => "Pune"],
    ["name" => "Ben", "city" => "Delhi"],
    ["name" => "Cy", "city" => "Pune"],
];

$byCity = array_reduce($people, function (array $groups, array $person): array {
    $groups[$person["city"]][] = $person["name"];
    return $groups;
}, []);

print_r($byCity);
Output
OUTPUT
Array
(
    [Pune] => Array
        (
            [0] => Ana
            [1] => Cy
        )

    [Delhi] => Array
        (
            [0] => Ben
        )

)

When a loop is clearer

array_reduce() is neat for small totals. For anything with several steps, a foreach is easier to read.

index.php
PHP
<?php
$prices = [100, 250, 50];
$total = 0;

foreach ($prices as $price) {
    $total += $price;
}

echo $total;
Output
OUTPUT
400

For plain sums, array_sum() is the shortest. Use array_reduce() when the combining rule is your own.

lightbulb
Map, filter, reduce
These three work well together: filter the items you want, map them into the shape you need, reduce them to a single answer.