tags:

views:

49

answers:

3

I want to know whether the array $arr has duplicate elements.

+3  A: 

Check out array_unique.

Emil Vikström
+8  A: 

array_unique() should work:

if (count(array_unique($arr)) == count($arr)) 
  echo "Array does not contain duplicate elements"; 
else
  echo "Array contains duplicate elements";
Pekka
A: 

I'm not sure there is a built in function for that. But you could do

if (count($arr) == count(array_unique($arr))
{
    //array has no unique elements
}
Decko
Arrays can't have duplicate keys. :)
deceze
re: deceze: which is also why `array_flip(array_flip($arr))` has the same result as `array_unique($arr)` (is quicker, too).
pinkgothic
@pinkgothic Nice trick, but I'd still go with `array_unique` for readability. :)
deceze
**@deceze** : Agreed. And since array key types are restricted, the `array_flip()` version doesn't always work, either! But if you're just working with `int` and `string` values in your array, it's an option. Which is good, since if you have really large arrays (say, > 100 elements), `array_unique()` is cripplingly slow. :(
pinkgothic
Just got back from lunch, clearly I needed it :)
Decko