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

April 22, 2018 —John Koster

The average method is simply an alias of the avg method, and can be used in exactly the same way.

#Signature

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

#Example Use

The following example demonstrates the usage of the average method:

1// Results in 12.5
2collect([5, 10, 15, 20])->avg();
3 
4// Results in 12.5
5collect([5, 10, 15, 20])->average();

#Using average With Higher Order Messages

The average 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 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->average->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.