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 does 'final class' and 'final function' (final method) mean in PHP?

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

How to order a Laravel hasMany relationship?

What is the null coalescing operator in PHP7?

How to run an artisan command from a controller

How to round a number in JS?

How to show a specific view file for certain error codes?

How to redirect your website to a new domain/location in .htaccess

What is the max size, by default, of GET variables?

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?