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.

5
  • you mean you need a more efficient way? Commented Jan 11, 2012 at 13:26
  • Are there just two dimensions or can there be arbitrary dimensions? Commented Jan 11, 2012 at 13:27
  • @Gumbo just two dimensions as in the example . Commented Jan 11, 2012 at 13:31
  • Would it suffice just to check for duplicate id values? Commented Jan 11, 2012 at 13:34
  • thanks for replying, yes that would be enough Commented Jan 11, 2012 at 13:37

2 Answers 2

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";
Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.