php: check if an array has duplicates

前端 未结 15 2293
情深已故
情深已故 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:45
    function hasDuplicate($array){
      $d = array();
      foreach($array as $elements) {
        if(!isset($d[$elements])){
          $d[$elements] = 1;
        }else{
          return true;
        } 
      } 
      return false;
    }
    
    0 讨论(0)
  • 2020-11-27 04:45

    You can do it like that way also: This will return true if unique else return false.

    $nofollow = (count($modelIdArr) !== count(array_unique($modelIdArr))) ? true : false;
    
    0 讨论(0)
  • 2020-11-27 04:48
    $duplicate = false;
    
     if(count(array) != count(array_unique(array))){
       $duplicate = true;
    }
    
    0 讨论(0)
  • 2020-11-27 04:54

    Here's my take on this… after some benchmarking, I found this to be the fastest method for this.

    function has_duplicates( $array ) {
        return count( array_keys( array_flip( $array ) ) ) !== count( $array );
    }
    

    …or depending on circumstances this could be marginally faster.

    function has_duplicates( $array ) {
        $array = array_count_values( $array );
        rsort( $array );
        return $array[0] > 1;
    }
    
    0 讨论(0)
  • 2020-11-27 04:54

    Keep it simple, silly! ;)

    Simple OR logic...

    function checkDuplicatesInArray($array){
        $duplicates=FALSE;
        foreach($array as $k=>$i){
            if(!isset($value_{$i})){
                $value_{$i}=TRUE;
            }
            else{
                $duplicates|=TRUE;          
            }
        }
        return ($duplicates);
    }
    

    Regards!

    0 讨论(0)
  • 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]!

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