Its my first post in stackoverflow. I've started programming since 3 weeks ago. now I'm on operator. I'm a bit curious about union in array operators. I have this code
<!DOCTYPE html>
<html>
<body>
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$c = array(5, 6, 7, 8);
$d = array(9, 10, 11, 12);
print_r($x + $y + $d + $c); // union of $x and $y
?>
</body>
</html>
i have tried all combination that possible, but for $c and $d, if i 'union' them, it always show only one of them. e.g i union $d + $c the output is:
Array ( [0] => 9 [1] => 10 [2] => 11 [3] => 12
Not a single array from $c shown there. Why doess it happen sensei??
It's because $c
and $d
have matching keys. From docs on array union: "For keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored."
print_r($x + $y + $d + $c);
will overwrite the keys.
Instead use array_merge()
.
Array_merge is what you need.
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$c = array(5, 6, 7, 8);
$d = array(9, 10, 11, 12);
print_r(array_merge($x, $y, $d, $c)); // union of $x and $y