问题
I would like to check if my array has any duplicates and return the duplicated values in an array. I want this to be as efficient as possible.
Example :$array = array(1,2,2,4,5)
function returndup($array) should return 2 ;
if array is array(1,2,1,2,5);
it should return an array with 1,2
Also the initial array is always 5 positions long
回答1:
this will be ~100 times faster than array_diff
$dups = array();
foreach(array_count_values($arr) as $val => $c)
if($c > 1) $dups[] = $val;
回答2:
You can get the difference of the original array and a copy without duplicates using array_unique and array_diff_assoc:
array_diff_assoc($arr, array_unique($arr))
回答3:
function array_dup($ar){
return array_unique(array_diff_assoc($ar,array_unique($ar)));
}
Should do the trick.
回答4:
You can do like this:
function showDups($array)
{
$array_temp = array();
foreach($array as $val)
{
if (!in_array($val, $array_temp))
{
$array_temp[] = $val;
}
else
{
echo 'duplicate = ' . $val . '<br />';
}
}
}
$array = array(1,2,2,4,5);
showDups($array);
Output:
duplicate = 2
回答5:
in addition to gumbo's answer:
function returndup($arr)
{
return array_diff_key($arr, array_unique($arr));
}
回答6:
function returndup($array)
{
$results = array();
$duplicates = array();
foreach ($array as $item) {
if (in_array($item, $results)) {
$duplicates[] = $item;
}
$results[] = $item;
}
return $duplicates;
}
回答7:
I have found another way to return duplicates in an array
function printRepeating($arr, $size)
{
$i;
$j;
for($i = 0; $i < $size; $i++)
for($j = $i + 1; $j < $size; $j++)
if($arr[$i] == $arr[$j])
echo $arr[$i], " ";
}
printRepeating($array, sizeof($array,0);
来源:https://stackoverflow.com/questions/3450022/check-and-return-duplicates-array-php