Home  >  Article  >  php教程  >  php array_merge函数使用需要注意的一个问题,phparray_merge

php array_merge函数使用需要注意的一个问题,phparray_merge

WBOY
WBOYOriginal
2016-06-13 09:08:44844browse

php array_merge函数使用需要注意的一个问题,phparray_merge

使用php语言的array_merge函数时,以为相同的键名会覆盖,但是请看如下代码:
复制代码 代码如下:
$a1 = array(1=>'abc', 3=>10);
$a2 = array(1=>'efg', 3=>20);
print_r(array_merge($a1, $a2));

会输出什么?我们预想中的是:
复制代码 代码如下:
Array
(
    [1] => efg
    [3] => 20
)

实际上输出的是:

复制代码 代码如下:
Array
(
    [0] => abc
    [1] => 10
    [2] => efg
    [3] => 20
)

不但没有被覆盖,而且数字键被重新连续索引了。

起初以为这个是bug,后来翻了php手册 http://php.net/manual/zh/function.array-merge.php

「如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。」

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn