How to calculate average of array in php?

Member

by ryleigh , in category: PHP General , 8 months ago

How to calculate average of array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 8 months ago

@ryleigh 

You can calculate the average of an array in PHP by summing up all the elements in the array and then dividing the sum by the number of elements in the array. Here's an example:

1
2
3
4
5
6
7
$array = [2, 4, 6, 8, 10];

$sum = array_sum($array);
$count = count($array);
$average = $sum / $count;

echo "The average of the array is: " . $average;


This will output:

1
The average of the array is: 6