Home >Backend Development >PHP Problem >How to find the average total score in php array
How to calculate the average total score in a php array: 1. Create a PHP sample file; 2. Define an array $scores containing integer values; 3. Use the "count()" function to get the values of the elements in the array The quantity is stored in the variable $count; 4. Define the total score variable $sum and use the "array_sum()" function to calculate the sum of the array elements; 5. Define the average score variable $average and divide the sum by the number of elements to get the average score ;6. Output $sum and $average.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
How to calculate the average score of a php array:
Use the count function to get the number of elements in the array.
Use the array_sum function to calculate the sum of array elements.
Divide the sum by the number of elements to get the average score.
The following is a code example:
<?php $scores = array(85, 90, 78, 89, 92); // 计算平均分和总分 $count = count($scores); $sum = array_sum($scores); $average = $sum / $count; echo "总分:" . $sum . "<br>"; echo "平均分:" . $average; ?>
The output result is:
总分:434 平均分:86.8
Among them, the array $scores contains five scores, using the count() function Get the length of an array and use the array_sum() function to calculate the sum of all elements. Finally divide the sum by the number of elements to get the average score.
The above is the detailed content of How to find the average total score in php array. For more information, please follow other related articles on the PHP Chinese website!