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 force non www in htaccess

PHP Date commonly used formats

How to undelete a soft deleted Eloquent row?

What are PHP's PSRs?

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to select what columns to return when calling ::all()

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to make multiple routes share the same URL structure or URL parameters

How to get table column names from a database table in Eloquent?

Remove trailing slash (redirect to remove trailing slash) in .htaccess