How to remove duplicate values from an array in PHP

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

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

相关标签:
24条回答
  • 2020-11-22 03:51

    try this short & sweet code -

    $array = array (1,4,2,1,7,4,9,7,5,9);
    $unique = array();
    
    foreach($array as $v){
      isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
      }
    
    var_dump($unique);
    

    Output -

    array(6) {
      [0]=>
      int(1)
      [1]=>
      int(4)
      [2]=>
      int(2)
      [3]=>
      int(7)
      [4]=>
      int(9)
      [5]=>
      int(5)
    }
    
    0 讨论(0)
  • 2020-11-22 03:52

    Use array_unique().

    Example:

    $array = array(1, 2, 2, 3);
    $array = array_unique($array); // Array is now (1, 2, 3)
    
    0 讨论(0)
  • 2020-11-22 03:52

    There can be multiple ways to do these, which are as follows

    //first method
    $filter = array_map("unserialize", array_unique(array_map("serialize", $arr)));
    
    //second method
    $array = array_unique($arr, SORT_REGULAR);
    
    0 讨论(0)
  • 2020-11-22 03:53

    That's a great way to do it. Might want to make sure its output is back an array again. Now you're only showing the last unique value.

    Try this:

    $arrDuplicate = array ("","",1,3,"",5);
    
    foreach (array_unique($arrDuplicate) as $v){
      if($v != "") { $arrRemoved[] = $v; }
    }
    print_r ($arrRemoved);
    
    0 讨论(0)
  • 2020-11-22 03:55
    $result = array();
    foreach ($array as $key => $value){
      if(!in_array($value, $result))
        $result[$key]=$value;
    }
    
    0 讨论(0)
  • 2020-11-22 03:56

    sometimes array_unique() is not the way, if you want get unique AND duplicated items...

    $unique=array("","A1","","A2","","A1","");
    $duplicated=array();
    
    foreach($unique as $k=>$v) {
    
    if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
     { unset($unique[$kt]);  $duplicated[]=$v; }
    
    }
    
    sort($unique); // optional
    sort($duplicated); // optional
    

    results on

    array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */
    
    array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */
    
    0 讨论(0)
提交回复
热议问题