Home Backend Development PHP Problem How to merge arrays in PHP array operation? Summary of common methods

How to merge arrays in PHP array operation? Summary of common methods

Nov 05, 2021 pm 12:09 PM
php array

In the previous article "PHP Array Operations Matching Search Elements and Key Names in Arrays" we introduced in detail the relevant knowledge of search matching for array operations in PHP. In this article we will continue Let’s take a look at some common operations of array merging in PHP. I hope everyone has to help!

How to merge arrays in PHP array operation? Summary of common methods

In the previous article we introduced the in_array function, array_search function and for array operations in PHP The array_key_exists function can be used to search and match elements in an array. Next, we can continue to look at some commonly used function operations related to arrays in PHP development work.

Let's introduce how to complete the merging of arrays in PHP. To achieve such an operation, we need to use the array_merge function and the array_merge_recursive function. Below we will introduce these two functions separately.

array_merge() function - overwrites the previous array elements with the same key name

In PHP we can passarray_merge() function is used to merge arrays, that is, to merge elements in multiple arrays into one array. The basic syntax format of the array_merge function is as follows:

array_merge(array1,array2,array3...)
Copy after login

What needs to be noted is: The parameter array123 is the array used for merging. This function can merge multiple arrays. If two elements or multiple elements have the same key name, after merging, the last element with their key name will overwrite the other elements.

This function can also merge an array. Yes, how do you say merging an array? What I mean at this time is that if the function inputs only one array, and the key name of this array is an integer, When "merged" by this function, the key names of the new array output are re-indexed starting from 0.

Next, let’s take a brief look at the use of the array_merge function through an example. The example is as follows:

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
Copy after login

Output result:

How to merge arrays in PHP array operation? Summary of common methods

In the above example, both arrays to be merged have elements with the key name "b". You can see the last element with the key name "b" in the final output result. "yellow" overwrites the previous elements, so there are only three elements in the final output.

Let’s take a look at the operation of “merging” an array. The example is as follows:

<?php
$a=array(3=>"red",4=>"green");
print_r(array_merge($a));
?>
Copy after login

Output result:

How to merge arrays in PHP array operation? Summary of common methods

In the above example, in an array that needs to be "merged", the key names of the array are all integers and are not indexed from 0. After merging through the array_merge function, the key names of the array change and are indexed from 0.

<strong><span style="max-width:90%">array_merge_recursive</span></strong>##Function - will not overwrite array elements with the same key name

In PHP, not only the array_merge function can merge arrays, but you need to know that the

array_merge_recursive function can also merge one or more arrays into one array. There is not much difference between the two. The difference you know is:

When two arrays that need to be merged have elements with the same key name, the two functions handle them differently. As mentioned in the example above,

array_mergeAfter the function is merged, the element whose key name is the last will overwrite other elements; however, the array_merge_recursive function can recurse elements with the same key name into an array without overwriting them.

Let’s take a look at the example above. The example is as follows:

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
echo  &#39;<br/>&#39;;
print_r(array_merge_recursive($a1,$a2));
?>
Copy after login

Output result:


How to merge arrays in PHP array operation? Summary of common methods

Through the above example You can see the difference between the two functions: It should be noted that the same two sets of arrays are merged through different functions, and the output results are different. Merged through the

array_merge function, the same element key name will be overwritten. The key names of elements merged through the array_merge_recursive function will not be overwritten.

Also, if you "merge" an array through the array_merge_recursive function, the result will be re-indexed from

0 just like the array_merge function.

The example is as follows:

<?php
$a=array(3=>"red",4=>"green");
print_r(array_merge_recursive($a));
?>
Copy after login

Output result:


How to merge arrays in PHP array operation? Summary of common methods##It can be seen from the above example

array_merge_recursive## The main difference between #function and

array_merge function is whether elements with the same key name will be overwritten.

<strong><span style="max-width:90%">+</span></strong>合并数组-覆盖后面相同键名的数组元素

通过+来进行数组的合并可以说是最简单的一种数组合并方法了,让我们直接通过示例来看一下用法,示例如下:

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
$a3=$a1+$a2;
print_r($a3);
?>
Copy after login

输出结果:

How to merge arrays in PHP array operation? Summary of common methods

由上述示例能够看出,通过+的方式来合并数组,和通过array_merge函数的方式来合并数组的区别就在于:

  • array_merge函数遇到相同键名的不同数组元素,合并之后会被覆盖掉,被覆盖的是前面的数组元素;

  • +遇到相同键名的不同数组元素进行合并,合并之后也会被覆盖掉,但是覆盖的元素是后面的数组元素。

<strong><span style="font-size: 20px;">array_combine</span></strong>函数-一组做键名一组做键值

在PHP中还有一个函数是array_combine函数,它能够将两个数组进行合并,并且其中一个数组的元素是合并后新数组的键名,另一个数组中的元素是合并后新数组的键值。

array_combine函数的基本语法格式如下:

array_combine(keys,values);
Copy after login

其中需要注意的是,参数keys表示的就是作为键名的数组,参数value表示的就是作为键值的数组,这两个数组中的元素个数一定要相同,也就是两个数组合并之后需要每个键名都有相对应的键值。

通过array_combine函数合并成功的话,返回的结果是合并成功后的数组,如果两个数组中的元素个数不相同那么返回的结果就是flase。

下面我们通过示例来看一下array_combine函数的应用,示例如下:

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
$a3 = array_combine($a1, $a2);
print_r($a3);
?>
Copy after login

输出结果:

How to merge arrays in PHP array operation? Summary of common methods

由此我们便通过array_combine函数完成了两个数组的合并,并且其中一个数组作为键名,另一个数组作为键值。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of How to merge arrays in PHP array operation? Summary of common methods. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles