php: check if an array has duplicates

前端 未结 15 2362
情深已故
情深已故 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

提交回复
热议问题