Reputation: 504
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
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
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
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
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