Can't concatenate 2 arrays in PHP

alex picture alex · Apr 16, 2010 · Viewed 100.6k times · Source

I've recently learned how to join 2 arrays using the + operator in PHP.

But consider this code...

$array = array('Item 1');

$array += array('Item 2');

var_dump($array);

Output is

array(1) { [0]=> string(6) "Item 1" }

Why does this not work? Skipping the shorthand and using $array = $array + array('Item 2') does not work either. Does it have something to do with the keys?

Answer

awgy picture awgy · Apr 16, 2010

Both will have a key of 0, and that method of combining the arrays will collapse duplicates. Try using array_merge() instead.

$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')

// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);

If the elements in your array used different keys, the + operator would be more appropriate.

$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');

// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;

Edit: Added a code snippet to clarify