PHP Implementation of Getting the Most Repeated Elements in an Array
- 2021-07-26 07:04:58
- OfStack
In this paper, the example tells the implementation method of PHP to get the most repeated elements in the array. Share it for your reference. The specific methods are 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 duplicate values of arrays
$array = array_count_values($array);
//2. Based on duplicate values Reverse sort
arsort($array);
if($length>0){
//3. Before returning $length Duplicate value
$array = array_slice($array, 0, $length, true);
}
return $array;
}
$array = array(1, 1, 1, 54, 3,4, 3,4, 3, 14, 3,4, 3,7,8,9,12,45,66,5,7,8,9,2,45);
$counts=mostRepeatedValues($array,5);
print_r($counts);
/* The output is:
Array
(
[3] => 5
[4] => 3
[1] => 3
[9] => 2
[45] => 2
)
*/
?>
I hope this article is helpful to everyone's PHP programming.