Tarun Baraiya
Tarun Baraiya

Reputation: 504

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 )

Upvotes: 1

Views: 212

Answers (4)

Captain Giraffe
Captain Giraffe

Reputation: 14705

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.

Upvotes: 1

verisimilitude
verisimilitude

Reputation: 5108

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

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

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

$c = array_unique($c);

Upvotes: 3

Guillaume Alouege
Guillaume Alouege

Reputation: 790

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

Upvotes: 0

Tomasz Struczyński
Tomasz Struczyński

Reputation: 3303

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));

Upvotes: 0

Related Questions