In PHP you can combine arrays using + or you can use array_merge. What’s the difference?

from  https://www.texelate.co.uk/blog/combining-arrays-using-plus-versus-array-merge-in-php

There are some differences between using associative arrays and sequential arrays. Associative arrays first:

$array1['foo'] = 'Bar 1';
$array2['foo'] = 'Bar 2';

print_r($array1 + $array2); // Array ( [foo] => Bar 1 )
print_r($array2 + $array1); // Array ( [foo] => Bar 2 )
print_r(array_merge($array1, $array2)); // Array ( [foo] => Bar 2 )
print_r(array_merge($array2, $array1)); // Array ( [foo] => Bar 1 )

 

The only difference is when using + the array doesn’t get overwritten but with array_merge it does.

When dealing with sequential arrays, however, the difference is greater.

$array1 = [1, 2, 3, 4, 5];
$array2 = [6, 7, 8, 9, 10];

print_r($array1 + $array2); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) 
print_r($array2 + $array1); // Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 [4] => 10 )
print_r(array_merge($array1, $array2)); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 ) 
print_r(array_merge($array2, $array1)); // Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 [4] => 10 [5] => 1 [6] => 2 [7] => 3 [8] => 4 [9] => 5 )

Because the arrays are automatically assigned numerical indices starting from 0 the results with + aren’t that different to using associative arrays — it's just that the keys are implicit in the code rather than explicitper an associative array.

The bigger difference is when standard arrays are merged. array_merge() doesn’t overwrite anything but rather joins the arrays up in the order you passed them to the function.

The documentation on the array_merge page explains it this way:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值