reduce()

reduce() boils a collection down to a single value.

Syntax$collection->reduce(function ($carry, $item) { return ...; }, $initial);

The reduce() method reduces the collection to a single value, passing the result of each iteration into the next. The second argument is the starting value (the carry).

It is perfect for totals, products, or building up a string.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • An order service reduces a collection of line-item prices into a single grand total to display in the checkout summary.
  • A reporting tool reduces a collection of daily visit counts into a running total to compute monthly traffic.
  • A permissions system reduces a user's role list into a merged set of capabilities by unioning the permission arrays.

More examples

Sum an array of numbers

Reduces the collection to a single integer by accumulating each value into the carry, starting from 0.

Example · php
$total = collect([10, 20, 30, 40])
    ->reduce(fn($carry, $item) => $carry + $item, 0);
// => 100

Compute an order total from line items

Multiplies quantity by price for each line item and accumulates the running total into a single float.

Example · php
$lines = collect([
    ['product' => 'Book',  'qty' => 2, 'price' => 12.99],
    ['product' => 'Pen',   'qty' => 5, 'price' =>  1.49],
    ['product' => 'Ruler', 'qty' => 1, 'price' =>  3.99],
]);

$total = $lines->reduce(
    fn($carry, $line) => $carry + ($line['qty'] * $line['price']),
    0.0
);
// => 37.42

Build an associative map with reduce

Uses reduce with an array initial value to build a keyed lookup map from a flat collection.

Example · php
$users = collect([
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
]);

$map = $users->reduce(function ($carry, $user) {
    $carry[$user['id']] = $user['name'];
    return $carry;
}, []);
// => [1 => 'Alice', 2 => 'Bob']

Discussion

  • Be the first to comment on this lesson.