简体   繁体   中英

Removing duplicates with array_unique giving wrong result

i have two array and i want to make unique array with single array

for example i have $a=array(3); and $b=array(1,2,3) so i want $c=array(1,2,3)

i made a code like:

            $a=array(3);
        $b=explode(',','1,2,3');
        $ab=$a+$b;
        $c=array_unique ($ab);
            print_r($c);

it gives me Array ( [0] => 3 [1] => 2 )

but i want to Array ( [0] => 1 [1] => 2 [2] => 3 )

$a = array(1,2,3,4,5,6);

$b = array(6,7,8,2,3);

$c = array_merge($a, $b);

$c = array_unique($c);

The operation

$ab = $a + $b

Is giving you a result you did not expect. The reason for this behaviour has been explained previously at PHP: Adding arrays together

$ab  is Array ( [0] => 3 [1] => 2 [2] => 3 )

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

array_merge provides a more intuitive behaviour.

Array merge, man. Array merge. Anyway, as this answer for similar question ( https://stackoverflow.com/a/2811849/223668 ) tells us:

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

If you have numeric keys (as in standard tables), they are for for sure duplicate in both arrays and the result is far from desired.

So the code should look like that:

$c = array_unique(array_merge($a, $b));

You need to use this array_merge to concat two array.

http://www.php.net/manual/en/function.array-merge.php

not

$ab = $a + $b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM