2

Possible Duplicate:
+ operator for array in PHP?

If $a and $b are both arrays, what is the result of $a + $b?

Community
  • 1
  • 1
OM The Eternity
  • 14,916
  • 40
  • 117
  • 180

5 Answers5

10

http://www.php.net/manual/en/language.operators.array.php

Union of $a and $b.

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

6
<?php

$a = array(1, 2, 3);
$b = array(4, 5, 6);
$c = $a + $b;

print_r($c);

results in this for me:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

BUT:

<?php

$a = array('a' => 1, 'b' => 2, 'c' => 3);
$b = array('d' => 4, 'e' => 5, 'f' => 6);
$c = $a + $b;

print_r($c);

results in:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
)

So it would appear that the answer here depends on how your arrays are keyed.

ceejayoz
  • 171,474
  • 40
  • 284
  • 355
1

My test

$ar1 = array('1', '2');
$ar2 = array('3', '4');
$test = $ar1 + $ar2;
print_r($test);

Array
(
    [0] => 1
    [1] => 2
)
Lizard
  • 41,806
  • 38
  • 103
  • 165
1

Now try this experiment

$a = array( 0 => 1,
            1 => 2,
            4 => 3
          );
$b = array( 2 => 4,
            4 => 5,
            6 => 6
          );
$c = $a + $b;

var_dump($c);
Mark Baker
  • 205,174
  • 31
  • 336
  • 380
-2

If you do something like $result = $a + $b; then $result will be assigned to the first argument, in this case $a.

Evernoob
  • 5,526
  • 8
  • 35
  • 49