Home > Backend Development > PHP Tutorial > PHP合并两个数组的两种方法:+和array_merge区别

PHP合并两个数组的两种方法:+和array_merge区别

WBOY
Release: 2016-06-20 13:04:26
Original
1057 people have browsed it

PHP合并两个数组的两种方法:+和array_merge区别

PHP中合并两个数组可以使用+或者array_merge,但这两个还是有区别的,清楚的了解这两中处理方法的区别对项目的快速开发来说还是非常有必要的。

 
主要区别是当两个或者多个数组中如果出现相同键名,需要注意以下两点:首先需要说明一下php里面数组按键名大约可以分为字符串(关联数组)或者数字(数值数组),这里就不讨论多维数组了。
 
(1)键名为数字(数值数组)时,array_merge()不会覆盖掉原来的值,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)。
 

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

下面通过几个具体的例子进行说明:

m:Array (

    [0] => a
    [1] => b
)
n:Array (
    [0] => c
    [1] => d
)
m+n 结果为 : Array (
    [0] => a
    [1] => b
)
array_merge(m,n)结果为 : Array (
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
m:Array (
    [1] => a
    [2] => b
)
n:Array (
    [2] => c
    [3] => d
)
m+n结果为 : Array (
    [1] => a
    [2] => b
    [3] => d
)
array_merge(m,n)结果为 : Array (
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
m:Array (
    [a] => a
    [b] => b
)
n:Array (
    [b] => c
    [d] => d
)
m+n结果为 : Array (
    [a] => a
    [b] => b
    [d] => d
)
array_merge(m,n)结果为 : Array (
    [a] => a
    [b] => c
    [d] => d
)


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template