I'm sure this is an extremely obvious question, and that there's a function that does exactly this, but I can't seem to find it. In PHP, I'd like to know if my array has duplicates in it, as efficiently as possible. I don't want to remove them like array_unique
does, and I don't particularly want to run array_unique
and compare it to the original array to see if they're the same, as this seems very inefficient. As far as performance is concerned, the "expected condition" is that the array has no duplicates.
I'd just like to be able to do something like
if (no_dupes($array))
// this deals with arrays without duplicates
else
// this deals with arrays with duplicates
Is there any obvious function I'm not thinking of?
How to detect duplicate values in PHP array?
has the right title, and is a very similar question, however if you actually read the question, he's looking for array_count_values.
I'm using this:
I don't know if it's the fastest but works pretty good so far
Here's my take on this… after some benchmarking, I found this to be the fastest method for this.
…or depending on circumstances this could be marginally faster.
As you specifically said you didn't want to use
array_unique
I'm going to ignore the other answers despite the fact they're probably better.Why don't you use array_count_values() and then check if the resulting array has any value greater than 1?
You can do it like that way also: This will return true if unique else return false.
I know you are not after
array_unique()
. However, you will not find amagicalobvious function nor will writing one be faster than making use of the native functions.I propose:
Adjust the second parameter of
array_unique()
to meet your comparison needs.⚡ PERFORMANCE SOLUTION ⚡
If you care about performance and micro-optimizations check this one-liner:
Description:
Function compares number of array elements in
$input_array
with array_flip'ed elements. Values become keys and guess what - keys must be unique in associative arrays so not unique values are lost and final number of elements is lower than original.As said in manual array keys can be only type of
int
orstring
so this is what you can have in original array values to compare, otherwise PHP will start casting with unexpected results.PROOF FOR 10M RECORDS ARRAY