Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a multidimensional array ($array) in which the entries look like:

{ ["upload/example.gif"]=> array(5) { 
     ["title"]=> string(12) "This is me" 
     ["excerpt"]=> string(24) "This is a photo of a tree" 
     ["img"]=> string(42) "upload/example.gif"
     ["link"]=> string(23) "http://www.google.co.uk" 
     ["source"]=> string(6) "custom" 
   }
}

I need to be able to remove any duplicate values in $array based on the key. So if my array was:

$array = array( ["upload/example.gif"] => etc....
                ["upload/tree.gif"] => etc....
                ["upload/example.gif"] => etc....)

I would be able to remove one of the ["upload/example.gif"] => etc.... arrays.

I have tried:

$array = array_map('unserialize', array_unique(array_map('serialize', $array)));

but that didn't work.

Thanks in advance.

share|improve this question
13  
You can't have duplicate keys (indexes) in an array. They will be overwritten. All keys are therefore automatically unique. – netcoder Apr 11 '11 at 15:02
1  
See php.net/manual/en/language.types.array.php If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten. – Treffynnon Apr 11 '11 at 15:03
@netcoder - I believe your comment qualifies as answer. – Álvaro G. Vicario Apr 11 '11 at 15:23
@netcoder - Thanks , this helped me solve the problem. – BobFlemming Apr 11 '11 at 15:29

1 Answer

up vote 0 down vote accepted

netcoder answered the question properly, I just wanted it to show up in the answer box (instead of comment).

You can't have duplicate keys in an associative array (or any array). By nature of it being an array you can be gauranteed to have unique keys.

BTW if you find duplicate data in different keys you can remove the redundant key by unsetting it.

unset($array['delete_me']);

http://php.net/manual/en/function.unset.php

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.