Open In App

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.

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.

<?php

function calculateAverage($array) {
    return array_sum($array) / count($array);
}

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

echo "The average is: " . $average;

?>

Output
The average is: 30

Explanation:

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.

<?php

function calculateAverage($array) {
    $sum = 0;
    $count = 0;
    foreach ($array as $value) {
        $sum += $value;
        $count++;
    }
    return $sum / $count;
}

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

echo "The average is: " . $average;

?>

Output
The average is: 30

Explanation:

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

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:

Article Tags :