Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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.25

An 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.33

The 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

Functions used in this recipe

  • array_sum — Returns the sum of the values in an array.
  • count — Returns the number of elements in an array.
  • round — Rounds a number to a given number of digits.

Thanks for reading!

Donate to the site — we work hard for you.