php return only duplicated entries from an array
function get_duplicates ($array) {
return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}
<?php
function array_not_unique($raw_array) {
$dupes = array();
natcasesort($raw_array);
reset($raw_array);
$old_key = NULL;
$old_value = NULL;
foreach ($raw_array as $key => $value) {
if ($value === NULL) { continue; }
if (strcasecmp($old_value, $value) === 0) {
$dupes[$old_key] = $old_value;
$dupes[$key] = $value;
}
$old_value = $value;
$old_key = $key;
}
return $dupes;
}
$raw_array = array();
$raw_array[1] = '[email protected]';
$raw_array[2] = '[email protected]';
$raw_array[3] = '[email protected]';
$raw_array[4] = '[email protected]'; // Duplicate
$common_stuff = array_not_unique($raw_array);
var_dump($common_stuff);
You will need to make your function case insensitive to get the "Hello" => "hello" result you are looking for, try this method:
$arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');
// Convert every value to uppercase, and remove duplicate values
$withoutDuplicates = array_unique(array_map("strtoupper", $arr));
// The difference in the original array, and the $withoutDuplicates array
// will be the duplicate values
$duplicates = array_diff($arr, $withoutDuplicates);
print_r($duplicates);
Output is:
Array
(
[3] => Hello
[4] => hello
)
Edit by @AlixAxel:
This answer is very misleading. It only works in this specific condition. This counter-example:
$arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'HELLO', 5=>'U');
Fails miserably. Also, this is not the way to keep duplicates:
array_diff($arr, array_unique($arr));
Since one of the duplicated values will be in array_unique
, and then chopped off by array_diff
.
Edit by @RyanDay:
So look at @Srikanth's or @Bucabay's answer, which work for all cases (look for case insensitive in Bucabay's), not just the test data specified in the question.
This is the correct way to do it (case-sensitive):
array_intersect($arr, array_unique(array_diff_key($arr, array_unique($arr))));
And a case-insensitive solution:
$iArr = array_map('strtolower', $arr);
$iArr = array_intersect($iArr, array_unique(array_diff_key($iArr, array_unique($iArr))));
array_intersect_key($arr, $iArr);
But @Srikanth answer is more efficient (actually, it's the only one that works correctly besides this one).