Laravel - Collections - Method Reduce

The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:

    
    $collection = collect([1, 2, 3]);
    
    $total = $collection->reduce(function ($carry, $item) {
        return $carry + $item;
    });
    
    // 6
	

The value for $carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:

    
    $collection->reduce(function ($carry, $item) {
        return $carry + $item;
    }, 4);
    
    // 10
	

The reduce method also passes array keys in associative collections to the given callback:

    
    $collection = collect([
        'usd' => 1400,
        'gbp' => 1200,
        'eur' => 1000,
    ]);
    
    $ratio = [
        'usd' => 1,
        'gbp' => 1.37,
        'eur' => 1.22,
    ];
    
    $collection->reduce(function ($carry, $value, $key) use ($ratio) {
        return $carry + ($value * $ratio[$key]);
    });
    
    // 4264