PHP中兩個數組合並可使用+或者array_merge,但之間仍是有區別的,並且這些區別若是瞭解不清楚項目中會要命的!php
主要區別是兩個或者多個數組中若是出現相同鍵名,鍵名分爲字符串或者數字,須要注意html
1)鍵名爲數字時,array_merge()後面的值將不會覆蓋原來的值,而是附加到後面,但+合併數組則會把最早出現的值做爲最終結果返回,而把後面的數組擁有相同鍵名的那些值「拋棄」掉(不是覆蓋)數組
2)鍵名爲字符串時,array_merge()此時會覆蓋掉前面相同鍵名的值,但+仍然把最早出現的值做爲最終結果返回,而把後面的數組擁有相同鍵名的那些值「拋棄」掉(不是覆蓋)。spa
須要注意的是數組鍵形式 '數字' 等價於 數字htm
$a = array('a', 'b'); $b = array('c', 'd'); $c = $a + $b; var_dump($a); var_dump(array_merge($a, $b)); //輸出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'd' (length=1) ++++++++++++++++++++++++++++++++++++++++++ $a = array( 0 => 'a', 1 => 'b' ); $b = array( 0 => 'c', 1 => 'b' ); $c = $a + $b; var_dump($c); var_dump(array_merge($a, $b)); //輸出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1) ++++++++++++++++++++++++++++++++++++++++++ $a = array('a', 'b'); $b = array( '0' => 'c', 1 => 'b' ); $c = $a + $b; var_dump($c); var_dump(array_merge($a, $b)); //輸出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1) ++++++++++++++++++++++++++++++++++++++++++ $a = array( 0 => 'a', 1 => 'b' ); $b = array( '0' => 'c', '1' => 'b' ); $c = $a + $b; var_dump($c); var_dump(array_merge($a, $b)); 輸出: array 0 => string 'a' (length=1) 1 => string 'b' (length=1) array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'b' (length=1)
對多個數組合並去重技巧blog
$a = array('1001','1002'); $b = array('1002','1003','1004'); $c = array('1003','1004','1005'); $d = count(array_flip($a) + array_flip($b) + array_flip($c));
延伸閱讀:ip