Check and return duplicates array php

2020-02-10 11:48发布

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

8条回答
啃猪蹄的小仙女
2楼-- · 2020-02-10 12:12

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
查看更多
冷血范
3楼-- · 2020-02-10 12:16

this will be ~100 times faster than array_diff

$dups = array();
foreach(array_count_values($arr) as $val => $c)
    if($c > 1) $dups[] = $val;
查看更多
登录 后发表回答