PASSWORD RESET

Your destination for complete Tech news

How to calculate the average of values in Collection in Laravel?

584 0
< 1 min read

To calculate the average of values in a Laravel collection, you can use the avg method. This method will return the average value of the given key of the items in the collection.

Here’s an example:

$collection = collect([
    ['name' => 'Alice', 'score' => 80],
    ['name' => 'Bob', 'score' => 90],
    ['name' => 'Charlie', 'score' => 70],
]);

$average = $collection->avg('score');

// $average is now 80

The avg method will return a float value representing the average.

If you want to calculate the average of a specific key for a nested collection, you can use the avg method in combination with the pluck method:

$collection = collect([
    ['name' => 'Alice', 'scores' => [80, 90]],
    ['name' => 'Bob', 'scores' => [70, 80]],
    ['name' => 'Charlie', 'scores' => [90, 100]],
]);

$average = $collection->pluck('scores')->avg();

// $average is now 85

Note that the avg method will return null if the collection is empty or if all the values of the given key are null.

If you want to calculate the average of all values in the collection, regardless of the keys, you can use the avg method in combination with the flatten method:

$collection = collect([[80, 90], [70, 80], [90, 100]]);
$average = $collection->flatten()->avg();

// $average is now 85

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.