How to find the average of an array
Short answer
Divide the sum by the count:
<?php
$marks = [4, 5, 3, 5];
echo array_sum($marks) / count($marks);Output:
4.25An empty array
Division by zero raises an error, so an empty array is checked separately:
<?php
function average(array $numbers): float
{
return $numbers === [] ? 0.0 : array_sum($numbers) / count($numbers);
}
var_dump(average([]));
echo round(average([10, 15, 12]), 2);Output:
float(0)
12.33The average of a field
Take the column out with array_column() first:
<?php
$orders = [['total' => 1200], ['total' => 800], ['total' => 1000]];
$totals = array_column($orders, 'total');
echo array_sum($totals) / count($totals);Output:
1000