I want to know whether the array $arr
has duplicate elements.
views:
49answers:
3
+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
2010-06-24 08:08:43
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
2010-06-24 08:10:22
Arrays can't have duplicate keys. :)
deceze
2010-06-24 08:12:06
re: deceze: which is also why `array_flip(array_flip($arr))` has the same result as `array_unique($arr)` (is quicker, too).
pinkgothic
2010-06-24 08:23:33
@pinkgothic Nice trick, but I'd still go with `array_unique` for readability. :)
deceze
2010-06-24 08:48:44
**@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
2010-06-24 09:47:31
Just got back from lunch, clearly I needed it :)
Decko
2010-06-24 10:45:06