What are some best practices for calculating averages in PHP, specifically when using foreach loops?

When calculating averages in PHP using foreach loops, it is important to keep track of both the sum of values and the count of elements in the array. This can be achieved by initializing variables to hold the sum and count before the loop, then updating them within the loop. Finally, the average can be calculated by dividing the sum by the count.

$values = [10, 20, 30, 40, 50]; // Sample array of values
$sum = 0; // Initialize sum variable
$count = 0; // Initialize count variable

foreach ($values as $value) {
    $sum += $value; // Add current value to sum
    $count++; // Increment count
}

$average = $sum / $count; // Calculate average
echo "The average is: " . $average; // Output average