tags:

views:

86

answers:

3

I've noticed recently in PHP you can do this.

$myNewArray = $oldArray + $someArray;

This looks completely different to anything I've seen before involving manipulating arrays in PHP.

How and why does it work? Are there any pitfalls?

I have recently started using it in some places where I may have used array_unshift() and array_merge().

+2  A: 

An operation is defined in the compiler for + when both operands are arrays. It does the intuitive operation of joining them.

Ignacio Vazquez-Abrams
+1 for the internal implementation, which I was interested in.
alex
+7  A: 

When in doubt, consult the documentation. The behavior is different from array_merge: array_merge appends/overwrites, + only appends.

Example:

<?php
$a = Array('foo'=>'bar','baz'=>'quux');
$b = Array('foo'=>'something else','xyzzy'=>'aaaa');

$c = $a + $b;
$d = array_merge($a,$b);

print_r($c);
print_r($d);

Output - as you see, array_merge overwrote the value from $a['foo'] with $b['foo']; $a+$b did not:

Array
(
    [foo] => bar
    [baz] => quux
    [xyzzy] => aaaa
)
Array
(
    [foo] => something else
    [baz] => quux
    [xyzzy] => aaaa
)
Piskvor
+1, good example, which is pretty much the same situation I was in today earlier.
alex
+2  A: 

One of the pitfalls is what happens when one of the variables is not an array.

array_merge:

Warning: array_merge(): Argument #2 is not an array in ...

+-operator:

Fatal error: Unsupported operand types in ...
Sjoerd
Could this be solved like so: `$myNewArray = (array) $oldArray + (array) $someArray;` ?
alex