array_merge和+号合并数组的区别

2018-03-01 11:13:09来源:segmentfault作者:sdbxpjzq人点击

分享
array_merge和+号合并数组的区别

先看栗子:


array_merge
$a = [51 => 12345];
$b = [10 => 5678];
$c = [];
$c = array_merge($c,$a,$b);
// Array ( [0] => 12345 [1] => 5678 )
$a = [51 => 12345];
$b = [51 => 5678];
$c = [];
$c = array_merge($c,$a,$b);
print_r($c); // Array ( [0] => 12345 [1] => 5678 )
$a = ['aa' => 12345];
$b = ['aa' => 5678];
$c = [];
$c = array_merge($c,$a,$b);
print_r($c);// Array ( [aa] => 5678 )

值覆盖情况:只考虑字符串索引的键值对, 用后边数组的值覆盖掉前面数组中键名相同的值


数字索引的值则不覆盖,同时保留


另外:array_merge()会重排两个数组的数字索引,+则不会。

+号
$a = [51 => 12345];
$b = [10 => 5678];
$c = [];
$C = $a+$b;
// Array ( [51] => 12345 [10] => 5678 )
$a = [51 => 12345];
$b = [51 => 5678];
$c = [];
$c = $a+$b;
print_r($c); // Array ( [51] => 12345 )
$a = ['aa' => 12345];
$b = ['aa' => 5678];
$c = [];
$c = $a+$b;
print_r($c);// Array ( [aa] => 12345 )

值覆盖情况:既考虑数字索引的键值对,也考虑字符串索引的键值对, 用前边数组的值覆盖后边的键名相同的值.

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台