Method: 1. Use sort() to sort the array, and use count() to find the length of the array; 2. Use "length%2==0" to determine whether the length is an even number or an odd number, and if it is an even number, the median It is "(array name [(length)/2] array name [((length)/2) 1])/2", otherwise it is "array [(length/2)-0.5".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php seeks a large array Median method
Implementation idea:
Use sort() to sort the array, Then use count() to find the length of the array
Determine whether the length of the array is even or odd
If the length of the array is even, then the median will bearr[ Array length/2] arr[(array length/2) 1]/ 2
.
If the array length is odd, the median will be the middle elementarr[(array length / 2) - 0.5]
.
Implementation code:
"; }else{ // 如果长度是奇数 echo "中位数为: ".($arr[($len/2)-0.5])."
"; } } $arr1=[1, 4, 7, 9]; f($arr1); $arr2=[1, 2, 4, 7, 9]; f($arr2); ?>
Recommended learning: "PHP video tutorial》
The above is the detailed content of How to find the median of a large array in php. For more information, please follow other related articles on the PHP Chinese website!