Why / how does merging arrays with + in PHP work?

I recently noticed in PHP that you can do this.

$myNewArray = $oldArray + $someArray; 

This looks completely different than anything I've seen before including array manipulation in PHP.

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

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

+4
source share
3 answers

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

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); 

Conclusion - as you can see, array_merge overwritten the value from $ a ['foo'] with $ b ['foo']; $ a + $ b:

 Array ( [foo] => bar [baz] => quux [xyzzy] => aaaa ) Array ( [foo] => something else [baz] => quux [xyzzy] => aaaa ) 
+8
source

The operation is defined in the compiler for + when both operands are arrays. This makes the intuitive operation of joining them.

+2
source

One of the errors 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 ... 
+1
source

Source: https://habr.com/ru/post/1303550/


All Articles