views:

36

answers:

6

Hello, 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

A: 
function returndup($array) 
{
    $results = array();
    $duplicates = array();
    foreach ($array as $item) {
        if (in_array($item, $results)) {
            $duplicates[] = $item;
        }

        $results[] = $item;
    }

    return $duplicates;
}
Ronn0
Not what the OP asked. They said it should be able to return more than one value.
Ash Burlaczenko
Now it returns an array of duplicates. In the first post there was no notice that is needs to return multiple duplicates, so don't blame me!
Ronn0
A: 

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))
Gumbo
A: 
function array_dup($ar){return array_unique(array_diff_assoc($ar,array_unique($ar)));}

Should do the trick.

Alex JL
A: 

in addition to gumbo's answer:

function returndup($arr)
{
  return array_diff_key($arr, array_unique($arr));
}
faebser
+2  A: 

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
+1  A: 

this will be ~100 times faster than array_diff

$dups = array();
foreach(array_count_values($arr) as $val => $c)
    if($c > 1) $dups[] = $val;
stereofrog