128 PHP合併陣列+與array_merge的區別分析

phpstory發表於2018-09-12

在PHP中可以使用array_merge函式和兩個陣列相加array+array的方式進行陣列合並,但兩者效果並不相同,下面為大家介紹兩者具體的使用區別.

區別如下:

 當下標為數值時,array_merge()不會覆蓋掉原來的值,但array+array合併陣列則會把最先出現的值作為最終結果返回,而把後面的陣列擁有相同鍵名的那些值“拋棄”掉(不是覆蓋). 

當下標為字元時,array+array仍然把最先出現的值作為最終結果返回,而把後面的陣列擁有相同鍵名的那些值“拋棄”掉,但array_merge()此時會覆蓋掉前面相同鍵名的值. 

例子1:

程式碼:

$arr1 = ['PHP', 'apache'];
$arr2 = ['PHP', 'MySQl', 'HTML', 'CSS'];
$mergeArr = array_merge($arr1, $arr2);
$plusArr = $arr1 + $arr2;
var_dump($mergeArr);
var_dump($plusArr);

結果
$mergeArr:

array (size=6)
  0 => string 'PHP' (length=3)
  1 => string 'apache' (length=5)
  2 => string 'PHP' (length=3)
  3 => string 'MySQl' (length=5)
  4 => string 'HTML' (length=4)
  5 => string 'CSS' (length=3)

$plusArr

array (size=4)
  0 => string 'PHP' (length=3)
  1 => string 'apache' (length=5)
  2 => string 'HTML' (length=4)
  3 => string 'CSS' (length=3

例子2:

程式碼:

$arr1 = ['PHP', 'a'=>'MySQl'];
$arr2 = ['PHP', 'MySQl', 'a'=>'HTML', 'CSS'];
$mergeArr = array_merge($arr1, $arr2);
$plusArr = $arr1 + $arr2;
var_dump($mergeArr);
var_dump($plusArr);

結果
$mergeArr:

array (size=5)
  0 => string 'PHP' (length=3)
  'a' => string 'HTML' (length=4)
  1 => string 'PHP' (length=3)
  2 => string 'MySQl' (length=5)
  3 => string 'CSS' (length=3)

$plusArr

array (size=4)
  0 => string 'PHP' (length=3)
  'a' => string 'MySQl' (length=5)
  1 => string 'MySQl' (length=5)
  2 => string 'CSS' (length=3)

例子3:

程式碼:

$arr1 = ['PHP', 'a'=>'MySQl','6'=>'CSS'];
$arr2 = ['PHP', 'MySQl', 'a'=>'HTML', 'CSS'];
$mergeArr = array_merge($arr1, $arr2);
$plusArr = $arr1 + $arr2;
var_dump($mergeArr);
var_dump($plusArr);

結果:

$mergeArr

array (size=6)
  0 => string 'PHP' (length=3)
  'a' => string 'HTML' (length=4)
  1 => string 'CSS' (length=3)
  2 => string 'PHP' (length=3)
  3 => string 'MySQl' (length=5)
  4 => string 'CSS' (length=3)

$plusArr

array (size=5)
  0 => string 'PHP' (length=3)
  'a' => string 'MySQl' (length=5)
  6 => string 'CSS' (length=3)
  1 => string 'MySQl' (length=5)
  2 => string 'CSS' (length=3)

相關文章