array_merge和+號合併數組的區別

array_merge和+號合併數組的區別

先看栗子:php

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 )

值覆蓋狀況: 只考慮字符串索引的鍵值對, 用後邊數組的值覆蓋掉前面數組中鍵名相同的值數組

數字索引的值則不覆蓋,同時保留code

另外: 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 )

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

相關文章
相關標籤/搜索