PHP合并两个数组的两种方法:+和array_merge区别
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
)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.
