1

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 )

Tarun Baraiya
  • 506
  • 1
  • 9
  • 30

4 Answers4

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);
verisimilitude
  • 5,077
  • 3
  • 30
  • 35
1

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.

Community
  • 1
  • 1
Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
0

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));
Community
  • 1
  • 1
Tomasz Struczyński
  • 3,273
  • 23
  • 28
0

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