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.php150 chars6 lines
Output:
main.php18 chars2 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.
gistlibby LogSnag