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
Two ways to do it efficiently that I can think of:
inserting all the values into some sort of hashtable and checking whether the value you're inserting is already in it(expected O(n) time and O(n) space)
sorting the array and then checking whether adjacent cells are equal( O(nlogn) time and O(1) or O(n) space depending on the sorting algorithm)
stormdrain's solution would probably be O(n^2), as would any solution which involves scanning the array for each element searching for a duplicate
$hasDuplicates = count($array) > count(array_unique($array));
Will be true
if duplicates, or false
if no duplicates.
Php has an function to count the occurrences in the array http://www.php.net/manual/en/function.array-count-values.php
Find this useful solution
function get_duplicates( $array ) {
return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}
After that count result if greater than 0 than duplicates else unique.
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.
I'm using this:
if(count($array)==count(array_count_values($array))){
echo("all values are unique");
}else{
echo("there's dupe values");
}
I don't know if it's the fastest but works pretty good so far