PHP Function To Work Out Average Values In Array

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.

Just out of interest I did the same test but without using function calls, just including the code that works out the averages in the benchmark timing function. It turns out that the first function is slightly faster when using short arrays, but is still significantly slower than the second function for longer arrays.

For simplicities sake you should probably just stick to the second function, but if speed is a big issue when finding the average of a small array then use the first function.

Add new comment

The content of this field is kept private and will not be shown publicly.
6 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.