Find Average from Array in PHP using array_reduce() Function

Another way to find the average is by using the array_reduce() function, which can be used to iteratively reduce the array to a single value (in this case, the sum of its elements).

PHP
<?php

function calculateAverage($array) {
    $sum = array_reduce($array, function($carry, $item) {
        return $carry + $item;
    }, 0);
    
    return $sum / count($array);
}

// Driver code
$arr = [10, 20, 30, 40, 50];
$average = calculateAverage($arr);

echo "The average is: " . $average;

?>

Output
The average is: 30

Explanation:

  • calculateAverage Function: This function uses array_reduce() to calculate the sum of the array’s elements and then divides the sum by the count of elements to find the average.
  • array_reduce() Function: Takes three arguments – the array, a callback function, and the initial value for the carry. The callback function is applied iteratively to each element of the array, with $carry being the result of the previous iteration.

How to Find Average from Array in PHP?

Given an array containing some elements, the task is to find the average of the array elements. Finding the average of values in an array is a common task in PHP programming. It involves summing all the elements in the array and then dividing the sum by the number of elements.

Table of Content

  • Using array_sum() and count() Functions
  • Using foreach Loop
  • Using array_reduce() Function

Similar Reads

Find Average from Array using array_sum() and count() Functions

The basic method to find the average is by using the array_sum() function to calculate the sum of the array elements and the count() function to find the number of elements in the array....

Find Average from Array in PHP using foreach Loop

If you want more control over the calculation, you can use a foreach loop to iterate through the array and calculate the sum and count manually....

Find Average from Array in PHP using array_reduce() Function

Another way to find the average is by using the array_reduce() function, which can be used to iteratively reduce the array to a single value (in this case, the sum of its elements)....