How to calculate the average of values in a numeric collection in illuminate/collections?

To calculate the average of values in a numeric collection using Illuminate/Collections, you can follow these steps:

  1. Firstly, import the required class at the top of your file:
use Illuminate\Support\Collection;
  1. Initialize a new Collection object with your numeric values:
$collection = collect([1, 2, 3, 4, 5]);
  1. Use the avg() method to calculate the average of the numeric values in the collection:
$average = $collection->avg();
  1. You can then use the $average variable to display or perform further operations with the calculated average.

Here's a complete example:

use Illuminate\Support\Collection; $collection = collect([1, 2, 3, 4, 5]); $average = $collection->avg(); echo "Average: " . $average;

This will output:

Average: 3