php: check if an array has duplicates

前端 未结 15 2425
情深已故
情深已故 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 04:58

    The simple solution but quite faster.

    $elements = array_merge(range(1,10000000),[1]);
    
    function unique_val_inArray($arr) {
        $count = count($arr);
        foreach ($arr as $i_1 => $value) {
            for($i_2 = $i_1 + 1; $i_2 < $count; $i_2++) {
                if($arr[$i_2] === $arr[$i_1]){
                    return false;
                }
            }
        }
        return true;
    }
    
    $time = microtime(true);
    unique_val_inArray($elements);
    echo 'This solution: ', (microtime(true) - $time), 's', PHP_EOL;
    

    Speed - [0.71]!

提交回复
热议问题