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
<?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:

  • calculateAverage Function: This function uses a foreach loop to iterate through the array and calculate the sum and count of its elements.
  • $sum and $count Variables: These variables keep track of the sum of the array’s elements and the number of elements, respectively.
  • $sum / $count: Calculates the average by dividing the sum by the count.

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)....