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 query mysql using PDO in PHP?

What are the SPL data structures

How does PHP compare objects?

How to set the Expires header in .htaccess

How to set up an alias to map one directory to another destination

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

How to find out what version of Laravel you are using?

How to replace values in a string, in JS

How do you launch the PHP interactive shell?

How to install and use jpegoptim on Linux CentOS