How to remove duplicate values from an array in PHP

后端 未结 24 1471
故里飘歌
故里飘歌 2020-11-22 03:40

How can I remove duplicate values from an array in PHP?

相关标签:
24条回答
  • 2020-11-22 04:00
    $array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
    
    // Deleting the duplicate items
    $result = array_unique($array);
    print_r($result);
    

    ref : Demo

    0 讨论(0)
  • 2020-11-22 04:01

    Remove duplicate values from an associative array in PHP.

    $arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );
    
    foreach($arrDup as $k =>  $v){
      if(!( isset ($hold[$v])))
          $hold[$v]=1;
      else
          unset($arrDup[$k]);
    }
    

    Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )

    0 讨论(0)
  • 2020-11-22 04:06

    Depending on the size of your array, I have found

    $array = array_values( array_flip( array_flip( $array ) ) );
    

    can be faster than array_unique.

    0 讨论(0)
  • 2020-11-22 04:06

    If you concern in performance and have simple array, use:

    array_keys(array_flip($array));
    

    It's many times faster than array_unique.

    0 讨论(0)
  • 2020-11-22 04:07

    We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...

    $array = array (1,3,4,2,1,7,4,9,7,5,9);
        $data=array();
        foreach($array as $value ){
    
            $data[$value]= $value;
    
        }
    
        array_keys($data);
        OR
        array_values($data);
    
    0 讨论(0)
  • 2020-11-22 04:08

    Here I've created a second empty array and used for loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array. If not then it'll add that item to second array with array_push.

    $a = array(1,2,3,1,3,4,5);
    $count = count($a);
    $b = [];
    for($i=0; $i<$count; $i++){
        if(!in_array($a[$i], $b)){
            array_push($b, $a[$i]);
        }
    }
    print_r ($b);
    
    0 讨论(0)
提交回复
热议问题