php: check if an array has duplicates

前端 未结 15 2294
情深已故
情深已故 2020-11-27 04:07

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

相关标签:
15条回答
  • 2020-11-27 05:04

    ⚡ PERFORMANCE SOLUTION ⚡

    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.

    PROOF FOR 10M RECORDS ARRAY

    • Most voted solution: 14.187316179276s
    0 讨论(0)
  • 2020-11-27 05:06

    You can do:

    function has_dupes($array) {
        $dupe_array = array();
        foreach ($array as $val) {
            if (++$dupe_array[$val] > 1) {
                return true;
            }
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-11-27 05:06

    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?

    0 讨论(0)
提交回复
热议问题