find the average of a list of numbers in php

To find the average of a list of numbers in PHP, you can use an array to store the numbers, a loop to iterate through the array and calculate the sum, and then divide the sum by the number of elements in the array to get the average.

Here's an example code snippet:

main.php
$numbers = array(2, 4, 6, 8, 10); // array of numbers
$sum = 0; // initialize sum to 0

// loop through the array and add each element to the sum
foreach ($numbers as $num) {
    $sum += $num;
}

$count = count($numbers); // get the number of elements in the array
$average = $sum / $count; // divide the sum by the count to get the average

echo "The average is: " . $average; // output the result
399 chars
13 lines

This will output:

main.php
The average is: 6
18 chars
2 lines

related categories

gistlibby LogSnag