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

How to make Apache force download of files (in .htaccess)

How to add a name prefix to all routes in a group?

How to sort an array of dates and times?

How to check if a relation was loaded on an Eloquent model already?

How does PHP compare objects?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

What is WordPress default Apache .htaccess rules?

What kind of database field type should you (normally) use for foreign keys?

How to install jpegtran for Linux CentOS

How to check if a user is logged in, inside a blade file?