Home  >  Article  >  Backend Development  >  How to get the most repeated elements in an array in PHP_PHP Tutorial

How to get the most repeated elements in an array in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:14:22918browse

How to get the most repeated elements in an array in PHP

This article describes the implementation method of getting the most repeated elements in an array in PHP. Share it with everyone for your reference. The specific method is as follows:

The code is as follows:

/**
*
* 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 array
$array = array_count_values($array);
//2. Sort in reverse order based on repeated values ​​
arsort($array);
if($length>0){
//3. Return the previous $length repeated 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 result is:
Array
(
[3] => 5
[4] => 3
[1] => 3
[9] => 2
[45] => 2
)
*/
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/909795.htmlTechArticleHow to get the most repeated elements in an array using PHP. This article explains how to get the most repeated elements in an array using PHP. Implementation method. Share it with everyone for your reference. The specific method is as follows...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn