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