Can't concatenate 2 arrays in PHP

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?


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


Use array_merge()
See the documentation here:
http://php.net/manual/en/function.array-merge.php

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.


+ is called the Union operator, which differs from a Concatenation operator (PHP doesn't have one for arrays). The description clearly says:

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

With the example:

$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b;

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

Since both your arrays have one entry with the key 0 , the result is expected.

To concatenate, use array_merge .

链接地址: http://www.djcxy.com/p/58948.html

上一篇: 在PHP中设置数组的理论联盟

下一篇: 无法连接PHP中的2个数组