PHP: how to obtain the most repeated elements in an array
This example describes how PHP can obtain the most repeated elements in an array. Share it with you for your reference. The specific method is as follows:
The Code is as follows:
<? Php
/**
*
* Created on 2014-4-1
* @ Param array $ array
* @ Param int [optional] $ length
* @ Return array
*/
Function mostRepeatedValues ($ array, $ length = 0 ){
If (emptyempty ($ array) or! Is_array ($ array )){
Return false;
}
// 1. Calculate the repeated value of the array
$ Array = array_count_values ($ array );
// 2. sort by repeated values in reverse order
Arsort ($ array );
If ($ length> 0 ){
// 3. returns the first $ length duplicate value
$ Array = array_slice ($ array, 0, $ length, true );
}
Return $ array;
}
$ Array = array (1, 1, 1, 54, 3, 3, 3, 14, 3, 3, 7, 8, 9, 12, 45, 9, 2, 45 );
$ Counts = mostRepeatedValues ($ array, 5 );
Print_r ($ counts );
/* The output result is:
Array
(
[3] => 5
[4] => 3
[1] => 3
[9] => 2
[45] => 2
)
*/
?>