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:

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.




Posting about Python and Laravel

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Is legacy software keeping you from disrupting your industry?

Informatica in Data Warehouse

git error: invalid object Error building trees

Getting Started with the HTML5 Canvas — Part 3

Updating Profile Images Stored on AWS S3 Buckets Using React Frontend and Rails API Backend

TronVerse AMA transcript

Software Engineer: Responsibilities, Roles, Salary

Remington Reed Completes AEM Sites Architect Certification

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Posting about Python and Laravel

More from Medium

Deploy Laravel Project

How to implement Highchart JS

Laravel 9 released!

Optimized way to save the sort order Into DB using “SortableJs, Vue draggable next or react-dnd…

Todo list with two drag area and sortable item