find the average of all elements in an array in php

To find the average of all elements in an array in PHP, you can use the array_sum() function to calculate the sum of all elements and the count() function to get the total number of elements in the array. Then, divide the sum by the count to get the average.

Here's the code:

main.php
$numbers = array(2, 4, 6, 8, 10);
$count = count($numbers);
$sum = array_sum($numbers);
$average = $sum / $count;
echo "The average is: " . $average;
150 chars
6 lines

Output:

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

In this example, the array contains the numbers 2, 4, 6, 8, and 10. We first use the count() function to get the total number of elements in the array, which is 5. Then, we use the array_sum() function to calculate the sum of all elements in the array, which is 30. Finally, we divide the sum by the count to get the average, which is 6.

related categories

gistlibby LogSnag