Method: 1. Sort the array in ascending order, and use "array_pop(array)" and "array_shift(array)" to remove the maximum and minimum values; 2. Use "count(array)" and "array_sum( Array)" to obtain the array length and element sum; 3. Use "element sum/array length" to calculate the average.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Remove the largest php array Method of averaging after values and minimum values
1. Remove the maximum and minimum values from the array
Use sort () Sort the array in ascending order
After sorting, the first element of the array is the minimum value, and the last element is the maximum value. Just use the array_pop() and array_shift() functions Just delete these two values.
array_pop(): Delete the last element in the array.
array_shift(): Delete the first element in the array.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(1,45,9,52,0,-5,21,-1,40); sort($arr); var_dump($arr); array_pop($arr); //去掉最大值 array_shift($arr); //去掉最小值 var_dump($arr); ?>
2. Statistics of the array length and the sum of array elements after removing the maximum and minimum values
Because the array_pop() and array_shift() functions will modify the original array, you can directly use the count() function to obtain the processed original array length.
$len=count($arr); echo "处理后的数组长度为:".$len;
Use array_sum() directly to get the sum of array elements:
$sum=array_sum($arr); echo "<br>处理后的数组元素之和为:".$sum;
3. Find the average: Use the "sum of array elements" divided by the "array length"
$num=$sum/$len; echo "<br>平均数为:".$num;
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove the maximum and minimum values from a php array and then calculate the average. For more information, please follow other related articles on the PHP Chinese website!