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条回答
Juvenile、少年°
2楼-- · 2020-02-10 11:57

in addition to gumbo's answer:

function returndup($arr)
{
  return array_diff_key($arr, array_unique($arr));
}
查看更多
贪生不怕死
3楼-- · 2020-02-10 11:57

$duplicate_array = array();

  for($i=0;$i<count($array);$i++){

    for($j=0;$j<count($array);$j++){

      if($i != $j && $array[$i] == $array[$j]){

        if(!in_array($array[$j], $duplicate_array)){

          $duplicate_array[] = $array[$j];

        }

      }

    }    

  }
查看更多
家丑人穷心不美
4楼-- · 2020-02-10 12:02
function array_dup($ar){
   return array_unique(array_diff_assoc($ar,array_unique($ar)));
}

Should do the trick.

查看更多
再贱就再见
5楼-- · 2020-02-10 12:03

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))
查看更多
Bombasti
6楼-- · 2020-02-10 12:10
function returndup($array) 
{
    $results = array();
    $duplicates = array();
    foreach ($array as $item) {
        if (in_array($item, $results)) {
            $duplicates[] = $item;
        }

        $results[] = $item;
    }

    return $duplicates;
}
查看更多
一纸荒年 Trace。
7楼-- · 2020-02-10 12:10

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);
查看更多
登录 后发表回答