How to remove duplicate values from an array in PHP

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

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

24条回答
  •  礼貌的吻别
    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 */
    

提交回复
热议问题