Home  >  Article  >  Backend Development  >  php Get duplicate data in array_PHP tutorial

php Get duplicate data in array_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:54:181114browse

Two days ago, I needed to find duplicate data in a php array. I summarized two methods and shared them with you here. Please pay attention
(1) Use the functions provided by php, array_unique and array_diff_assoc to achieve
[php]
function FetchRepeatMemberInArray($array) {
// Get the array with duplicate data removed
$unique_arr = array_unique ( $array );
// Get an array of duplicate data
$repeat_arr = array_diff_assoc ( $array, $unique_arr );
Return $repeat_arr;
}

// Test case
$array = array (
        'apple',
        'iphone',
       'miui',
        'apple',
        'orange',
        'orange'                                                                            );
$repeat_arr = FetchRepeatMemberInArray ( $array );
print_r ( $repeat_arr );

?>

(2) Write your own function to implement this function, using two for loops

[php]
function FetchRepeatMemberInArray($array) {
$len = count ( $array );
for($i = 0; $i < $len; $i ++) {
for($j = $i + 1; $j < $len; $j ++) {
If ($array [$i] == $array [$j]) {
                     $repeat_arr [] = $array [$i];
break;
                                                                                                                                               } 
}  
Return $repeat_arr;
}

// Test case
$array = array (
        'apple',
        'iphone',
       'miui',
        'apple',
        'orange',
        'orange'                                                                            );
$repeat_arr = FetchRepeatMemberInArray ( $array );
print_r ( $repeat_arr );

?>


http://www.bkjia.com/PHPjc/477959.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477959.htmlTechArticleTwo days ago, I needed to find duplicate data in the php array. I summarized two methods, here Share it with everyone, please pay attention (1) Use the functions provided by php, array_unique and a...
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