11th March 2008 - 3 minutes read time
Working out the average of a bunch of values is quite a common task, but rather than looping through the array, adding together values as you go and the using the count() function to find out the average at the end.
function average($array)
{
$total = 0;
foreach ($array as $item) {
$total += $item;
};
return $total/count($array);
}
However, a much simpler way of doing things is just to use the PHP function array_sum(), which adds up all of the values in the array. Because this is done by the PHP engine it should take less time than using a for loop.
function average($array) {
return array_sum($array) / count($array);
}
Tests show that the second function is only just faster when using short (2 or 3 items) arrays, but the second function is significantly faster when looking at longer (10 or more) arrays.