array_merge和+號合併陣列的區別

sdbxpjzq發表於2019-02-16

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 ) 

值覆蓋情況: 既考慮數字索引的鍵值對,也考慮字串索引的鍵值對, 用前邊陣列的值覆蓋後邊的鍵名相同的值.

相關文章