How to find the average value of items in a Laravel Collection?

Laravel: How to find the average value of items in a Laravel Collection?

Use the avg() method. You can provide a value indicating which key to average (first example) or not
(2nd example).

  1. $average = collect(
  2.         [
  3.                 ['foo' => 10],
  4.                 ['foo' => 10],
  5.                 ['foo' => 20],
  6.                 ['foo' => 40]
  7.         ]
  8.         )->avg('foo');
  9.  
  10. // 20
  11.  
  12. $average = collect(
  13.         [1, 1, 2, 4]
  14.         )->avg();
  15.  
  16. // 2

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to find the average value of items in a Laravel Collection?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

What are macros in Laravel?

How to see all of the options for an artisan command?

How to add comments in PHP

How to eager load multiple levels of relationships in Eloquent?

How to fix the MySQL related "Specified key was too long error" error in Laravel

How to replace values in a string, in JS

Set PHP config Variables (like ini_set) with .htaccess

301 Redirect a single URL in .htaccess to a new location

How to block IPv6 IP addresses in .htaccess

How to create random numbers in JS?