操作符+,在前一個數的基礎上插入後一個數組,如果有相同的拋棄,而array_merge 是在前一個參數基礎上插入後一個參數,如果有相同用的key 用後一個覆蓋。實例如下:
php > $a = array('a'=>'1','b'=>'2','c'=>'3'); php > $b = array('c'=>3,'d'=>'4','e'=>'5'); php > $c = $a+$b; php > $d = array_merge($a,$b); php > var_dump($c,$d); array(5) { 'a' => string(1) "1" 'b' => string(1) "2" 'c' => string(1) "3" 'd' => string(1) "4" 'e' => string(1) "5" } array(5) { 'a' => string(1) "1" 'b' => string(1) "2" 'c' => int(3) 'd' => string(1) "4" 'e' => string(1) "5" } php > $e = array_merge($b,$a); php > var_dump($e); array(5) { 'c' => string(1) "3" 'd' => string(1) "4" 'e' => string(1) "5" 'a' => string(1) "1" 'b' => string(1) "2" } php > $f=$b+$a; php > var_dump($f); array(5) { 'c' => int(3) 'd' => string(1) "4" 'e' => string(1) "5" 'a' => string(1) "1" 'b' => string(1) "2" }
當兩邊都是索引數組時,使用array_merge 可能會引起索引重置,如下面這種情況:
php > $a = array(); php > $b = array(1=>'data'); php > $c = $a+$b; php > $d = array_merge($a,$b); php > var_dump($c,$d); array(1) { [1] => string(4) "data" } array(1) { [0] => string(4) "data" }
所以,當使用+來合並兩個索引數組,值可能會被丟棄,而array_merge就不會,會把重復的索引重置:
php > $a = array(1=>'one',2=>'two',3=>'three'); php > $b = array(3=>'three',4=>'four',5=>'five'); php > $c = $a+$b; php > $d = array_merge($a,$b); php > var_dump($c,$d); array(5) { [1] => string(3) "one" [2] => string(3) "two" [3] => string(5) "three" [4] => string(4) "four" [5] => string(4) "five" } array(6) { [0] => string(3) "one" [1] => string(3) "two" [2] => string(5) "three" [3] => string(5) "three" [4] => string(4) "four" [5] => string(4) "five" }