Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: check if an array has duplicates

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.

like image 520
Mala Avatar asked Jun 29 '10 23:06

Mala


People also ask

How do I check if an array has duplicates?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How check array is unique or not in PHP?

PHP array_unique() Functionprint_r(array_unique($a));

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.


1 Answers

I know you are not after array_unique(). However, you will not find a magical obvious function nor will writing one be faster than making use of the native functions.

I propose:

function array_has_dupes($array) {    // streamline per @Felix    return count($array) !== count(array_unique($array)); } 

Adjust the second parameter of array_unique() to meet your comparison needs.

like image 152
Jason McCreary Avatar answered Sep 23 '22 13:09

Jason McCreary