主页 M

php数组ARRAY_MERGE和+的区别

2015-12-17 网页编程网 网页编程网

这个例子比较全面的比较了PHP合并两个数组常见的方法array_merge和+的区别:

$array1 = array(
    'test1' => 'test1',
    'test2' => 'test2',
    8       => '9',
    '10'    => '1010',
    's10'   => 's10',
);

$array2 = array(
    'test1' => 'test1+',
    'test2' => 'test2+',
    '++'    => '++',
    8       => '9999',
    '10'    => '10101010',
    's10'   => 's10101010',
);

$result = array_merge($array1,$array2);
$result2 = $array1+$array2;
var_dump($result);
var_dump($result2);
exit;

结果:

array (size=8)
  'test1' => string 'test1+' (length=6)
  'test2' => string 'test2+' (length=6)
  0 => string '9' (length=1)
  1 => string '1010' (length=4)
  's10' => string 's10101010' (length=9)
  '++' => string '++' (length=2)
  2 => string '9999' (length=4)
  3 => string '10101010' (length=8)
 
array (size=6)
  'test1' => string 'test1' (length=5)
  'test2' => string 'test2' (length=5)
  8 => string '9' (length=1)
  10 => string '1010' (length=4)
  's10' => string 's10' (length=3)
  '++' => string '++' (length=2)

其实大多数时候合并数组,都会用array_merge,毕竟相同的键,一般情况都以后面的为准。注意array_merge合并数组,如果两个键相同并且是数字,无论是整形还是字符串数字,都会重新从0开始作为键。

阅读原文
阅读 4076
123 显示电脑版