array_merge与数组(array)相加的区别

array_merge与数组(array)相加的区别

之前每次面试 我发现面试到基础部分的时候 这个问题 出现的频率 特别高 ,
所以在这里写出来 , 加深下印象 也希望可以帮到更多的人.

例子1:

$a = ['one','two'];
$b = ['three','four','five'];
var_dump(array_merge($a,$b));
/*
array (size=5)
  0 => string 'one' (length=3)
  1 => string 'two' (length=3)
  2 => string 'three' (length=5)
  3 => string 'four' (length=4)
  4 => string 'five' (length=4)
  */
  
var_dump(array_merge($b,$a));
  /*
array (size=5)
  0 => string 'three' (length=5)
  1 => string 'four' (length=4)
  2 => string 'five' (length=4)
  3 => string 'one' (length=3)
  4 => string 'two' (length=3)
  */
var_dump($a+$b);
  /*
array (size=3)
  0 => string 'one' (length=3)
  1 => string 'two' (length=3)
  2 => string 'five' (length=4)
  */
var_dump($b+$a);
  /*
array (size=3)
  0 => string 'three' (length=5)
  1 => string 'four' (length=4)
  2 => string 'five' (length=4)
*/

例子2:

$a = ['name'=>'php','mysql'];
$b = ['DB'=>'mysql','test','name'=>'golang'];
var_dump(array_merge($a , $b));
/*
array (size=4)
  'name' => string 'golang' (length=6)
  0 => string 'mysql' (length=5)
  'DB' => string 'mysql' (length=5)
  1 => string 'test' (length=4)
*/
var_dump($a + $b );
/*
array (size=3)
  'name' => string 'php' (length=3)
  0 => string 'mysql' (length=5)
  'DB' => string 'mysql' (length=5)
*/

例子3:

$a = ['mysql','name'=>'php',3=>'html'];
$b = [1=>'test','name'=>'golang',2=>'mysqli','javascript'];
var_dump(array_merge($a , $b));
/*
array (size=6)
  0 => string 'mysql' (length=5)
  'name' => string 'golang' (length=6)
  1 => string 'html' (length=4)
  2 => string 'test' (length=4)
  3 => string 'mysqli' (length=6)
  4 => string 'javascript' (length=10)
*/
var_dump( $a + $b );
/*
array (size=5)
  0 => string 'mysql' (length=5)
  'name' => string 'php' (length=3)
  3 => string 'html' (length=4)
  1 => string 'test' (length=4)
  2 => string 'mysqli' (length=6)
*/

从以上例子可以看出:
当array_merge( a r r A , arrA, arrA,arrB) 会将$arrB数的成员 全部追加到参数arrA数组中去,
arrB将会覆盖掉arrA中的 字符类型 同键名值,其余的依次追加,
并且会将所有key值重新排列,关联数组自定义 字符类型 key值除外(参考例三)

而arrayA+arrayB时,不管是什么数组 arrayA都会将arrayB中的同键名值抛弃,其余追加至arrayA中,key不会重新排列

你可能感兴趣的:(PHP)