Search

Calculating Averages Using Collections in Laravel

March 23, 2016 —John Koster

The avg method is a useful method for calculating the average of all items in the collection. The avg method defines an optional $key parameter, which can be used to specify what property of the collection should be averaged. If no key is provided, the method assumes the collection contains numeric values and will average all items of the collection. If a key is provided, the method will look for a matching array key or object property on all items in the array and then average the value of those items. For example, the following code will a new Collection instance and calculate the average of all items in the collection:

1 
2// Calculate the average of some array.
3$average = collect([5, 10, 15, 20])->avg();

After the above code has executed $average would contain the value 12.5, which is the average of 5, 10, 15, and 20.

The previous example was fairly simple, and in most cases the collections will be more complicated. For example, consider the following sample collection of products:

1 
2$products = collect([
3 ['name' => 'Shiny New Tablet', 'price' => 799.99],
4 ['name' => 'Not A Stylus (Digital Stylus)', 'price' => 99.99]
5]);

We can calculate the average price of all items in the collection by simply passing in a value for the $key parameter. The value of $key must correspond to some key or property of the nested arrays or objects:

1// Calculate the average price of all products.
2$averagePrice = $products->avg('price');

After the above code has been executed, the $averagePrice variable would contain the value 449.99.

The avg method will also work on collections of objects, and is used exactly the same way. If we created a new collection of products, where all the individual products are objects instead of nested arrays, we will get the same result:

1 
2// Create a new collection where all the items
3// are objects instead of nested arrays
4// using the `map` method to convert.
5$objectProducts = $products->map(function($item, $key) {
6 // Cast each product array into an object.
7 return (object)$item;
8});

Now we can call the avg method on our new $objectProducts collection:

1// Calculate the average price of all products.
2$objectAveragePrice = $objectProducts->avg('price');

Like before, the value of $objectAveragePrice would contain the value 449.99.

#Averaging Nested Collections

The avg method will also work on nested array items or object properties. You can specify which nested property to average by using "dot" notation.

For example, in the following array of products it is still possible to use the avg method to calculate the average product price:

1 
2// Create a new collection with nested
3// product details.
4$nestedProductsDetails = collect([
5 [
6 'name' => 'Shiny New Tablet',
7 'details' => [
8 'price' => 799.99
9 ]
10 ],
11 [
12 'name' => 'Not A Stylus (Digital Stylus)',
13 'details' => [
14 'price' => 99.99
15 ]
16 ]
17]);
18 
19// Calculate the average product price by
20// supplying the `$key` using "dot"
21// notation.
22$averageProductPrice = $nestedProductDetails->avg('details.price');

As with all the previous examples, the $averageProductPrice variable would contain the value 449.99.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.