Home > Article > Backend Development > PHP method to count the 10 most frequently occurring numbers in a numerical array_PHP Tutorial
This article mainly introduces the method of counting the 10 most frequently occurring numbers in a numerical array in PHP. Related usage skills involving array_count_values and arsort methods in php are very practical. Friends in need can refer to it
The example in this article describes the method of PHP counting the 10 most frequently occurring numbers in a numerical array. Share it with everyone for your reference. The specific analysis is as follows:
This question belongs to the TOPK category. It is used to count the frequency of word occurrences and make reports. It is commonly used in data statistics!
The php code is as follows:
?
2 3
4 56 13 14 |
//Randomly generate numerical array
for($i=0;$i<1000;$i ){<🎜>
<🎜>$ary[]=rand(1,1000);<🎜>
<🎜>}<🎜>
<🎜>//Count the number of occurrences of all values in the array<🎜>
<🎜>$ary=array_count_values($ary);<🎜>
<🎜>arsort($ary);//Sort in reverse order<🎜>
<🎜>$i=1;<🎜>
<🎜>foreach($ary as $key=>$value){
if($i<=10){<🎜>
<🎜>printf("Number: %d appears %d times ",$key,$value); }else{ break; } $i ; } unset($ary); |
1 2 3 4 5 6 7 8 9 10 | Number: 255 appears 6 times in total Number: 443 Appeared 5 times in total Number: 906 appears 5 times in total Number: 623 appears 5 times in total Number: 586 appears 4 times in total Number: 660 appears 4 times in total Number: 873 appears 4 times in total Number: 208 appears 4 times in total Number: 247 appears 4 times in total Number: 240 appears 4 times in total |