php数组合并用加号(+)和用array_merge()的区别

用加号合并数组:既考虑数字索引的键值对,也考虑字符串索引的键值对,用前边数组的值覆盖后边的键名相同的值; 用array_merge()合并数组:只考虑字符串索引的键值对,用后边数组的值覆盖掉前面数组中键名相同的值,数字索引的值则不覆盖,同时保留

用加号合并数组:既考虑数字索引的键值对,也考虑字符串索引的键值对,用前边数组的值覆盖后边的键名相同的值;
用array_merge()合并数组:只考虑字符串索引的键值对,用后边数组的值覆盖掉前面数组中键名相同的值,数字索引的值则不覆盖,同时保留
另外:array_merge()会重排两个数组的数字索引,"+"则不会
第一先看数组元素:
php"><?php
$a = array('r'=>1,2,3,4);
var_dump('a',$a);
$b = array('r'=>5,6,7,8);
var_dump('b',$b);
$c = array('r'=>5,6,7,8,9);
var_dump('c',$c);
 
var_dump('a+b',$a+$b);
var_dump('a+c', $a+$c);
 
var_dump('amb', array_merge($a, $b));
var_dump('amc', array_merge($a, $c));
第二看输出:
string 'a' (length=1)
array
  'r' => int 1
  0 => int 2
  1 => int 3
  2 => int 4
string 'b' (length=1)
array
  'r' => int 5
  0 => int 6
  1 => int 7
  2 => int 8
string 'c' (length=1)
array
  'r' => int 5
  0 => int 6
  1 => int 7
  2 => int 8
  3 => int 9
 
string 'a+b' (length=3)
array
  'r' => int 1
  0 => int 2
  1 => int 3
  2 => int 4
 
string 'a+c' (length=3)
array
  'r' => int 1
  0 => int 2
  1 => int 3
  2 => int 4
  3 => int 9
 
string 'amb' (length=3)
array
  'r' => int 5
  0 => int 2
  1 => int 3
  2 => int 4
  3 => int 6
  4 => int 7
  5 => int 8
string 'amc' (length=3)
array
  'r' => int 5
  0 => int 2
  1 => int 3
  2 => int 4
  3 => int 6
  4 => int 7
  5 => int 8
  6 => int 9
 

本文标题为:php数组合并用加号(+)和用array_merge()的区别

基础教程推荐