Can't concatenate 2 arrays in PHP

后端 未结 10 1111
终归单人心
终归单人心 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 13:03

    + 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.

提交回复
热议问题