1

I have an array like this:

Array(
   ["dest0"] => Array(
                  ["id"] => 1,
                  ["name"] => name1   
                 ),    
   ["dest1"] => Array(
                  ["id"] => 2,
                  ["name"] => name2  
                 ),   
  ["dest2"] => Array(
                  ["id"] => 3,
                  ["name"] => name3  
                 ),   
  ["dest3"] => Array(
                  ["id"] => 1,
                  ["name"] => name1   
                 )
);    

and want to check for duplicate values in it (like here dest0 and dest3 are duplicate), i dont want it to remove them like here , juste check if there's any.

Thanks.

Community
  • 1
  • 1
Mouna Cheikhna
  • 38,870
  • 10
  • 48
  • 69

2 Answers2

2

You can use following code to figure out duplicate (if any):

// assuming $arr is your original array
$narr = array();
foreach($arr as $key => $value) {
   $narr[json_encode($value)] = $key;
}
if (count($arr) > count($narr))
   echo "Found duplicate\n";
else
   echo "Found no duplicate\n";
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Based purely on checking for duplicate id rather than both id and name, but easily modified:

$duplicates = array();
array_walk($data, function($testValue, $testKey) use($data, &$duplicates){
                        foreach($data as $key => $value) {
                            if (($value['id'] === $testValue['id']) && ($key !== $testKey))
                                return $duplicates[$testKey] = $testValue;
                        }
                    } );

if (count($duplicates) > 0) {
    echo 'You have the following duplicates:',PHP_EOL;
    var_dump($duplicates);
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385