Combine two arrays

前端 未结 9 546
名媛妹妹
名媛妹妹 2020-11-22 15:47

I have two arrays like this:

array( 
\'11\' => \'11\',
\'22\' => \'22\',
\'33\' => \'33\',
\'44\' => \'44\'
);

array( 
\'44\' => \'44\',
\'55         


        
相关标签:
9条回答
  • 2020-11-22 16:02

    The new way of doing it with php7.4 is Spread operator [...]

    $parts = ['apple', 'pear'];
    $fruits = ['banana', 'orange', ...$parts, 'watermelon'];
    var_dump($fruits);
    

    Spread operator should have better performance than array_merge

    A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.

    0 讨论(0)
  • 2020-11-22 16:11

    You should take to consideration that $array1 + $array2 != $array2 + $array1

    $array1 = array(
    '11' => 'x1',
    '22' => 'x1' 
    );  
    
    $array2 = array(
    '22' => 'x2',
    '33' => 'x2' 
    );
    

    with $array1 + $array2

    $array1 + $array2 = array(
    '11' => 'x1',
    '22' => 'x1',
    '33' => 'x2'
    );
    

    and with $array2 + $array1

    $array2 + $array1 = array(  
    '11' => 'x1',  
    '22' => 'x2',  
    '33' => 'x2'  
    );
    
    0 讨论(0)
  • 2020-11-22 16:16

    https://www.php.net/manual/en/function.array-merge.php

    <?php
    $array1 = array("color" => "red", 2, 4);
    $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
    $result = array_merge($array1, $array2);
    print_r($result);
    ?>
    
    0 讨论(0)
提交回复
热议问题