Reduce an array in Laravel php
For Laravel Collections there is a method reduce()
for reducing the collection to a single value.
Suppose we have a Laravel Collection
We can use simple php foreach loop to iterate through the items and access to their costs and calculate the total cost like:
Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.
https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs
Alternative ( the better way ):
The alternative in Laravel is to use the reduce
method.
The reduce
method passes the result of each iteration into the subsequent iteration.
Note: This method does the same job as the method array_reduce
in PHP does.