$test = array('hi');
$test += array('test','oh');
var_dump($test);
What does +
mean for array in PHP?
$test = array('hi');
$test += array('test','oh');
var_dump($test);
What does +
mean for array in PHP?
It basically means array_merge()
, with the difference that duplicate keys will not be overwritten. This can look quite different from array_merge
though, e.g.
$array1 = array('one', 'two', 'foo' => 'bar');
$array2 = array('three', 'four', 'five', 'foo' => 'baz');
$array3 = $array1 + $array2;
print_r($array3);
print_r(array_merge($array1, $array2));
outputs:
Array
(
[0] => one // preserved from $array1
[1] => two // preserved from $array1
[foo] => bar // preserved from $array1
[2] => five // added from $array2
)
Array
(
[0] => one // preserved from $array1
[1] => two // preserved from $array1
[foo] => baz // overwritten from $array2
[2] => three // appended from $array2
[3] => four // appended from $array2
[4] => five // appended from $array2
)
See linked page for more examples.
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>
When executed, this script will print the following:
Union of $a and $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" } Union of $b and $a: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" }
not exactly like array_merge
Note that the plus operator for arrays ‘+’ is only one-dimensional, and is only suitable for simple arrays.
read more :
http://www.vancelucas.com/blog/php-array_merge-preserving-numeric-keys/
This operator takes the union of two arrays (same as array_merge, except that with array_merge duplicate keys are overwritten).
The documentation for array operators is found here.