Can't concatenate 2 arrays in PHP

后端 未结 10 1063
终归单人心
终归单人心 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:11

    It is indeed a key conflict. When concatenating arrays, duplicate keys are not overwritten.

    Instead you must use array_merge()

    $array = array_merge(array('Item 1'), array('Item 2'));
    
    0 讨论(0)
  • 2020-11-28 13:13

    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.

    0 讨论(0)
  • 2020-11-28 13:13

    This works for non-associative arrays:

    while(($item = array_shift($array2)) !== null && array_push($array1, $item));

    0 讨论(0)
  • 2020-11-28 13:16

    Try saying

    $array[] = array('Item 2'); 
    

    Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.

    0 讨论(0)
提交回复
热议问题