tags:

views:

366

answers:

4
$test = array('hi');
$test += array('test','oh');
var_dump($test);

What does + mean for array in PHP?

+13  A: 

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.

Gordon
+1  A: 

It will append the new array to the previous.

SorcyCat
+3  A: 

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/

Haim Evgi
No offense, but if you copy 1:1 from http://php.net/manual/en/language.operators.array.php, then why not add a link indicating so?
Gordon
@Gordon: I knew I'd read this text somewhere before...
R. Bemrose
i link to another site that i copy from him , www.vancelucas.com.....i am usually give a credit
Haim Evgi
+3  A: 

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.

Peter Smit