i want to retrieve all duplicated entries from a array, how can it be possible in php.
array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');
i want to return an array having hello
out put array
array(1 =>'Hello' ,2=>'hello');
i want to retrieve all duplicated entries from a array, how can it be possible in php.
array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');
i want to return an array having hello
out put array
array(1 =>'Hello' ,2=>'hello');
Try:
$arr2 = array_diff_key($arr, array_unique($arr));
case insensitive:
array_diff_key($arr, array_unique(array_map('strtolower', $arr)));
<?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
)
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;
}
What shiva srikanth (john) added but with the case insensitive comparison.