当前位置 : 首页 » 编程语言 » 正文

PHP合并数组+与array_merge的区别分析

分类 : 编程语言 | 发布时间 : 2018-04-21 09:06:21 | 浏览 : 0
主要区别是两个或者多个数组中如果出现相同键名,键名分为字符串或者数字,需要注意

1)键名为数字时,array_merge()不会覆盖掉原来的值,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)

2)键名为字符时,+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值

需要注意的是数组键形式 '数字' 等价于 数字
复制代码 代码如下:

$a = array('a','b');
$b = array('c', 'd');
$c = $a + $b;
var_dump($a);
var_dump(array_merge($a, $b));

$a = array(0 => 'a', 1 => 'b');
$b = array(0 => 'c', 1 => 'b');
$c = $a + $b;
var_dump($c);
var_dump(array_merge($a, $b));

$a = array('a', 'b');
$b = array('0' => 'c', 1 => 'b');
$c = $a + $b;
var_dump($c);
var_dump(array_merge($a, $b));

$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)
2 => string 'c' (length=1)
3 => string 'd' (length=1)

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)

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)

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)

相关阅读:

Find the last element of an array while using a foreach loop in PHP

Using AND/OR in if else PHP statement

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Download File to server from URL

PHP multidimensional array search by value

deny direct access to a folder and file by htaccess

What is the best IDE for PHP?

How do I get a YouTube video thumbnail from the YouTube API?

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

How can I prevent SQL injection in PHP?