Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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().

like image 304
alex Avatar asked Dec 23 '22 05:12

alex


1 Answers

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
)
like image 153
Piskvor left the building Avatar answered Dec 31 '22 22:12

Piskvor left the building