How to remove duplicate values from an array in PHP

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

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

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

    Use array_values(array_unique($array));

    array_unique: for unique array array_values: for reindexing

    0 讨论(0)
  • 2020-11-22 03:57
        if (@!in_array($classified->category,$arr)){        
                                        $arr[] = $classified->category;
                                     ?>
    
                <?php } endwhile; wp_reset_query(); ?>
    

    first time check value in array and found same value ignore it

    0 讨论(0)
  • 2020-11-22 03:58
    $arrDuplicate = array ("","",1,3,"",5);
     foreach(array_unique($arrDuplicate) as $v){
      if($v != "" ){$arrRemoved = $v;  }}
    print_r($arrRemoved);
    
    0 讨论(0)
  • 2020-11-22 03:59
    function arrayUnique($myArray)
    {
        $newArray = Array();
        if (is_array($myArray))
        {
            foreach($myArray as $key=>$val)
            {
                if (is_array($val))
                {
                    $val2 = arrayUnique($val);
                }
                else
                {
                    $val2 = $val;
                    $newArray=array_unique($myArray);
                    $newArray=deleteEmpty($newArray);
                    break;
                }
                if (!empty($val2))
                {
                    $newArray[$key] = $val2;
                }
            }
        }
        return ($newArray);
    }
    
    function deleteEmpty($myArray)
    {
        $retArray= Array();
        foreach($myArray as $key=>$val)
        {
            if (($key<>"") && ($val<>""))
            {
                $retArray[$key] = $val;
            }
        }
        return $retArray;
    }
    
    0 讨论(0)
  • 2020-11-22 04:00

    explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));

    This will take care of key associations and serialize the keys for the resulting new array :-)

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

    An alternative for array_unique() function..

    Using Brute force algorithm

    //[1] This our array with duplicated items

    $matches = ["jorge","melvin","chelsy","melvin","jorge","smith"];

    //[2] Container for the new array without any duplicated items

    $arr = [];

    //[3] get the length of the duplicated array and set it to the var len to be use for for loop

    $len = count($matches);

    //[4] If matches array key($i) current loop Iteration is not available in //[4] the array $arr then push the current iteration key value of the matches[$i] //[4] to the array arr.

    for($i=0;$i if(array_search($matches[$i], $arr) === false){ array_push($arr,$matches[$i]); } } //print the array $arr. print_r($arr); //Result: Array ( [0] => jorge [1] => melvin [2] => chelsy [3] => smith )

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