What's the difference between array_merge and array + array?

后端 未结 9 1609
遥遥无期
遥遥无期 2020-11-29 21:26

A fairly simple question. What\'s the difference between:

$merged = array_merge($array1, $array2);

and

$merged = $array1 +          


        
相关标签:
9条回答
  • 2020-11-29 21:44

    Yet another example (arrays without explicit keys; it's obvious regarding to how the operator + and array_merge work, but "obvious" things are simpler when seen ;))

    $a = array('apple');
    $b = array('orange', 'lemon');
    
    echo '$a + $b = ';             print_r($a + $b);
    echo 'array_merge($a, $b) = '; print_r(array_merge($a, $b));
    

    will give:

    $a + $b = Array
    (
        [0] => apple
        [1] => lemon
    )
    array_merge($a, $b) = Array
    (
        [0] => apple
        [1] => orange
        [2] => lemon
    )
    
    0 讨论(0)
  • 2020-11-29 21:49

    Please pay attention for another difference: the union (+) won't overwrite non-empty value with empty value (considering a same key), whereas array_merge will:

    $a = array('foo' => 'bar');
    $b = array('foo' => ''); // or false or 0
    
    print_r($a+$b);
    print_r(array_merge($a, $b);
    

    Outputs :

    Array
    (
        [foo] => bar
    )
    Array
    (
        [foo] => 0
    )
    
    0 讨论(0)
  • 2020-11-29 21:51

    I believe array_merge overwrites duplicate non_numeric keys while $array1 + $array2 does not.

    0 讨论(0)
  • 2020-11-29 21:54

    array_merge() causes all numeric keys found in the input arrays to be reindexed in the resultant array. The union operator + does not cause a reindex.

    0 讨论(0)
  • 2020-11-29 21:55

    Source: https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/

    Stop using array_merge($defaults, $options):

    function foo(array $options)
    {
       $options += ['foo' => 'bar'];
    
       // ...
    }
    

    Note: array_replace function exists since PHP5.3.

    0 讨论(0)
  • 2020-11-29 21:56

    So apparently if you change the order both union and merge will do the same thing

    $a = array('foo' => 'bar', 'x' => 'fromA');
    $b = array('foo' => null, 'x' => 'fromB');
    
    echo '$a+$b: ';
    var_dump($a+$b);
    
    echo '$b+$a: ';
    var_dump($b+$a);
    
    echo 'array_merge($a, $b): ';
    var_dump(array_merge($a, $b));
    
    echo 'array_merge($b, $a): ';
    var_dump(array_merge($b, $a));
    

    Outputs :

    $a+$b: array(2) {
      ["foo"]=>
      string(3) "bar"
      ["x"]=>
      string(5) "fromA"
    }
    $b+$a: array(2) {
      ["foo"]=>
      NULL
      ["x"]=>
      string(5) "fromB"
    }
    array_merge($a, $b): array(2) {
      ["foo"]=>
      NULL
      ["x"]=>
      string(5) "fromB"
    }
    array_merge($b, $a): array(2) {
      ["foo"]=>
      string(3) "bar"
      ["x"]=>
      string(5) "fromA"
    }
    

    Keep in mind the order of the arrays.

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