Two ways for php to get duplicate data in an array

  • 2020-06-23 00:04:29
  • OfStack

(1) Using the functions provided by php, array_unique and array_diff_assoc to achieve

 
<?php 
function FetchRepeatMemberInArray($array) { 
    //  Gets an array with deduplicated data  
    $unique_arr = array_unique ( $array ); 
    //  Gets an array of duplicate data  
    $repeat_arr = array_diff_assoc ( $array, $unique_arr ); 
    return $repeat_arr; 
} 

//  The test case  
$array = array ( 
        'apple', 
        'iphone', 
        'miui', 
        'apple', 
        'orange', 
        'orange'  
); 
$repeat_arr = FetchRepeatMemberInArray ( $array ); 
print_r ( $repeat_arr ); 
?> 

(2) Write your own function to achieve 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; 
} 

//  The test case  
$array = array ( 
        'apple', 
        'iphone', 
        'miui', 
        'apple', 
        'orange', 
        'orange'  
); 
$repeat_arr = FetchRepeatMemberInArray ( $array ); 
print_r ( $repeat_arr ); 
?> 


Related articles: