Search

Laravel 5 Collections: Calculating the Average Value of a Collection With avg

April 22, 2018 —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.

#Signature

1public function avg(
2 $callback = null
3);

#Example Use

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
23 ->avg('details.price');

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

#Using avg With Higher Order Messages

The avg method can also be used with higher order messaging, which allows us to invoke collection methods and access object instance properties using PHP's property accessors syntax. In the reject section, we created a Product class that was used to reject all products that were not on sale.

We will, again, take advantage of higher order messages to easily calculate the average price on a collection of Product instances:

1$products = collect([
2 [
3 'name' => 'Office Chair',
4 'price' => 399.99,
5 'onSale' => false
6 ],
7 [
8 'name' => 'Desk',
9 'price' => 199.34,
10 'onSale' => true
11 ]
12])->transform(function ($item) {
13 $product = new Product;
14 $product->name = $item['name'];
15 $product->price = $item['price'];
16 $product->onSale = $item['onSale'];
17 
18 return $product;
19});
20 
21$averagePrice = $products->avg->price;

After the above example has executed, the $averagePrice variable would hold the value 299.665.

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.