PHP Function To Work Out Average Values In Array

11th March 2008 - 2 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.

  1. function average($array)
  2. {
  3. $total = 0;
  4. foreach ($array as $item) {
  5. $total += $item;
  6. };
  7. return $total/count($array);
  8. }

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.

  1. function average($array) {
  2. return array_sum($array) / count($array);
  3. }

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.