array_merge 和+的区别

php有2个函数常用语数组合并,他们是array_merge+.本节来讲一下两者的区别.

索引数组

$arr1 = [1 => 'one', 3 => 'three'];
$arr2 = [1 => 'new one', 6 => 'six'];
$result1 = array_merge($arr1, $arr2);
$result2 = $arr1 + $arr2;

//output
$result1:
Array
(
    [0] => one
    [1] => three
    [2] => new one
    [3] => six
)

$result2:
Array
(
    [1] => one
    [3] => three
    [6] => six
)

结论:

  • array_merge就是简单的数组追加,即使索引相同也不会出现覆盖的情况。这也注定了新数组的索引会被重写。变为0,1,2,3….
  • +的方式在遇到索引相同时,保留前者抛弃后者

关联数组

$arr3 = ['name' => '张三', 'age' => 21];
$arr4 = ['name' => '李四', 'age' => 22];
$result3 = array_merge($arr3, $arr4);
$result4 = $arr3 + $arr4;
dd($result3);
dd($result4);

//output
//result3:
Array
(
    [name] => 李四
    [age] => 22
)
//result4:
Array
(
    [name] => 张三
    [age] => 21
)

结论

  • array_merge键名相同,后者覆盖前者
  • +依旧是保留前者抛弃后者

你可能感兴趣的:(array_merge 和+的区别)