PHP: how to obtain the most repeated elements in an array _ PHP Tutorial

Source: Internet
Author: User
PHP is used to obtain the most repeated elements in an array. PHP: how to obtain the most repeated elements in an array. This article describes how to use PHP to obtain the most repeated elements in an array. Share it with you for your reference. The specific method is as follows: PHP is used to obtain the most repeated elements in the 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:

/**
*
* 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
)
*/
?>

Examples in this article 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...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.