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
If you care about performance and micro-optimizations check this one-liner:
function no_dupes(array $input_array) {
return count($input_array) === count(array_flip($input_array));
}
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
or string
so this is what you can have in original array values to compare, otherwise PHP will start casting with unexpected results.
You can do:
function has_dupes($array) {
$dupe_array = array();
foreach ($array as $val) {
if (++$dupe_array[$val] > 1) {
return true;
}
}
return false;
}
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?