4 Ways to Find the Average of an Array in PHP

Updated: January 10, 2024 By: Guest Contributor Post a comment

Introduction

Finding the average of array values is a common task in PHP programming. There are multiple ways to calculate the average, each with its own use cases and performance implications. In this guide, we’ll explore several methods to compute the average and discuss their pros and cons.

4 Solutions

Solution 1: Using array_sum and count

This is the straightforward approach to calculating the average of an array. It involves using the built-in array_sum() function to sum the array values and then dividing by the count of the array elements using the count() function:

  • Sum all the array elements with array_sum().
  • Determine the number of elements with count().
  • Divide the sum by the number of elements.

Example:

$numbers = [1, 2, 3, 4, 5];
$average = array_sum($numbers) / count($numbers);
echo $average; // Output: 3

While this method is easy and works with any non-empty array, it is unsuitable for large arrays due to potential performance issues with array_sum().

Solution 2: Using foreach Loop

If you need more control over how array elements are processed or if they’re not all numerical, manually summing them using a foreach loop is a good approach:

  • Initialize a sum variable to zero.
  • Iterate over the array with foreach and add each value to the sum.
  • Divide the sum by the count of array elements.

Example:

$numbers = [1, 2, 3, 4, 5];
$sum = 0;
foreach ($numbers as $number) {
    $sum += $number;
}
$average = $sum / count($numbers);
echo $average; // Output: 3

This method is more efficient than the first for large datasets, as it avoids the overhead of additional function calls.

Solution 3: Using array_reduce

If you favor functional programming techniques, array_reduce() can be used to calculate the average in a more concise manner:

  • Define a custom sum function.
  • Use array_reduce() to apply this function and calculate the sum.
  • Divide by the size of the array.

Example:

$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item);
$average = $sum / count($numbers);
echo $average; // Output: 3

This solution is elegant but can incur a performance penalty compared to the foreach loop for large arrays due to the overhead of function calls in array_reduce().

Solution 4: Using array_map and array_sum

To handle more complex scenarios, such as calculating the average of an array of objects, you could use array_map() in conjunction with array_sum():

  • Map each object to its numerical value with array_map().
  • Sum the resulting array of numbers.
  • Divide by the number of objects.

Example:

$objects = [
    (object)['value' => 1],
    (object)['value' => 2],
    (object)['value' => 3],
    (object)['value' => 4],
    (object)['value' => 5]
];

$numeric_values = array_map(fn($obj) => $obj->value, $objects);
$average = array_sum($numeric_values) / count($numeric_values);

echo $average; // Output: 3

This method is versatile and allows for complex calculations, but does incur additional overhead due to both array_map() and array_sum() being used.

Conclusion

We have explored several ways to find the average of an array in PHP. While array_sum() and count() offer a simple solution, they may not be the best for performance in certain cases, especially with large datasets. Iterating manually using a foreach loop can be more efficient in such cases. For functional programming enthusiasts or complex data structures, array_reduce() and array_map() with array_sum() are valuable tools, albeit with additional function call overhead. Your choice should depend on the specific requirements of your project and the nature of the data you are dealing with.