Home >Backend Development >PHP Tutorial >How to get the most repeated elements in an array in PHP, php array_PHP tutorial

How to get the most repeated elements in an array in PHP, php array_PHP tutorial

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

PHP implementation method of getting the most repeated elements in an array, php array

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

Copy code 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 the repeated values ​​​​of the array
$array = array_count_values($array);
//2. Sort in reverse order based on duplicate 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
)
*/
?>
I hope this article will be helpful to everyone’s PHP programming design.

http://www.bkjia.com/PHPjc/909333.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/909333.htmlTechArticleThe implementation method of PHP getting the most repeated elements in the array, php array This article tells the example of PHP getting the most repeated elements in the array The implementation method of the element. Share it with everyone for your reference. Specifically...
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