Can't concatenate 2 arrays in PHP

后端 未结 10 1110
终归单人心
终归单人心 2020-11-28 12:49

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

But consider this code...

$array = array(\'Item 1\');

$array += array(\'Ite         


        
10条回答
  •  一整个雨季
    2020-11-28 12:54

    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

提交回复
热议问题