How to remove duplicate values from an array in PHP

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

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

24条回答
  •  佛祖请我去吃肉
    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);
    

提交回复
热议问题