Home > Article > Backend Development > php Get duplicate data in array_PHP tutorial
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 );
?>
[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 );
?>