Home Backend Development PHP Problem Let's talk in depth about the replacement element operation of PHP arrays

Let's talk in depth about the replacement element operation of PHP arrays

Apr 23, 2023 am 09:18 AM

PHP is a widely used server-side scripting language. It has powerful data processing capabilities and flexibility and is widely used in Web development. Among them, array is a very important data type, often used to store and operate data. In PHP, we can use built-in functions to perform various operations on arrays, such as adding, deleting, querying, sorting, traversing, etc. This article will focus on the replacement element operation of PHP arrays and provide specific code examples.

1. Common functions for replacing array elements

PHP provides multiple functions for replacing elements in arrays, of which the following three functions are the most commonly used:

  1. array_replace($array1, $array2)

This function replaces the elements in array 2 with the corresponding elements in array 1. If there are the same key names in array 1 or array 2, Then use the values ​​in the latter array to replace the values ​​in the previous array. Please look at the following code example:

$array1 = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$array2 = array('a' => 'apricot', 'd' => 'date');
$result = array_replace($array1, $array2);
print_r($result);
Copy after login

Execute the above code, you will get the following output:

Array
(
    [a] => apricot
    [b] => banana
    [c] => cherry
    [d] => date
)
Copy after login

As you can see, the key-value pair in array 1 ('a'=>'apple ') has been replaced by the key-value pair ('a'=>'apricot') in array 2, and the new key-value pair ('d'=>'date') in array 2 has also been added in the final result array.

  1. array_replace_recursive($array1, $array2)

This function is very similar to array_replace(), but it recursively replaces the elements in array 2 with those in array 1 corresponding element. If the value in array1 or array2 is an array, the key-value pairs in that value will also be replaced recursively. Please look at the following code example:

$array1 = array('a' => array('b' => 'blue', 'c' => 'cyan'), 'd' => 'black');
$array2 = array('a' => array('b' => 'brown', 'e' => 'emerald'));
$result = array_replace_recursive($array1, $array2);
print_r($result);
Copy after login

Execute the above code and you will get the following output:

Array
(
    [a] => Array
        (
            [b] => brown
            [c] => cyan
            [e] => emerald
        )

    [d] => black
)
Copy after login

As you can see, the key-value pair in array 1 ('a'=>array( 'b'=>'blue', 'c'=>'cyan')) has been replaced by the key-value pair in array 2 ('a'=>array('b'=>'brown', ' e'=>'emerald')). Moreover, the subarrays within the array are also replaced recursively.

  1. array_splice($array, $offset, $length, $replacement)

This function is used to delete the element at the specified position in the array and insert a new one at that position. Elements. Specifically, the $offset parameter represents the starting index position of the element to be deleted/replaced, the $length parameter represents the number of elements to be deleted (0 if no elements are deleted), and the $replacement parameter represents the new element to be inserted. Please look at the following code example:

$array = array('red', 'green', 'blue', 'yellow');
array_splice($array, 1, 2, array('purple', 'orange'));
print_r($array);
Copy after login

Execute the above code and you will get the following output:

Array
(
    [0] => red
    [1] => purple
    [2] => orange
    [3] => yellow
)
Copy after login

You can see that the 2 elements starting from index 1 in the original array ('green', 'blue') has been removed and two new elements ('purple', 'orange') have been inserted at index 1.

2. Application examples

Now, let’s take a look at how to use the above function to replace elements in a PHP array based on specific application scenarios.

  1. Application of replacement rules

Suppose we have an array in which the key names are the Chinese names of some plants and the key values ​​are their English names. Now, we want to replace the English names of some of these plants, such as "apple" with "orange" and "cherry" with "grape", leaving the rest unchanged. This can be achieved using the array_replace() function. Please look at the sample code below:

$plants = array('苹果' => 'apple', '香蕉' => 'banana', '樱桃' => 'cherry', '葡萄' => 'grape');
$rules = array('apple' => 'orange', 'cherry' => 'grape');
$newPlants = array_replace($plants, $rules);
print_r($newPlants);
Copy after login

Execute the above code and you will get the following output:

Array
(
    [苹果] => orange
    [香蕉] => banana
    [樱桃] => grape
    [葡萄] => grape
)
Copy after login

You can see that the key values ​​​​of "Apple" and "Cherry" have been separated. Replaced with "orange" and "grape" while leaving the rest of the key values ​​unchanged.

  1. Application of Multidimensional Array

Suppose we have a multidimensional array, the key name is the name of some cities, and the key value is an associative array, which contains The city's population, industry and other information. Now, we want to add and subtract the population of certain cities and save the results back to the original array. This can be achieved using the array_replace_recursive() function. The code is as follows:

$cities = array(
    '北京市' => array('人口' => 2154, '产业' => '政治、文化、金融、科技'),
    '上海市' => array('人口' => 2424, '产业' => '金融、贸易、科技、文化'),
    '广州市' => array('人口' => 1500, '产业' => '商贸、制造、物流、金融')
);
$rules = array(
    '北京市' => array('人口' => -100),
    '广州市' => array('人口' => 200)
);
$newCities = array_replace_recursive($cities, $rules);
print_r($newCities);
Copy after login

Execute the above code and you will get the following output:

Array
(
    [北京市] => Array
        (
            [人口] => 2054
            [产业] => 政治、文化、金融、科技
        )

    [上海市] => Array
        (
            [人口] => 2424
            [产业] => 金融、贸易、科技、文化
        )

    [广州市] => Array
        (
            [人口] => 1700
            [产业] => 商贸、制造、物流、金融
        )
)
Copy after login

As you can see, the population of Beijing has decreased by 1 million, and the population of Guangzhou has decreased by 1 million. The population of Shanghai increased by 2 million, while the information of Shanghai remained the same.

  1. Application of deleting specified elements

Suppose we have an array that stores the names and ages of several individuals. Now, we want to delete information for people who are 30 years or older. This can be achieved using the array_splice() function. The code is as follows:

$people = array(
    array('name' => '张三', 'age' => 25),
    array('name' => '李四', 'age' => 35),
    array('name' => '王五', 'age' => 28),
    array('name' => '赵六', 'age' => 42)
);
for ($i = count($people) - 1; $i >= 0; $i--) {
    if ($people[$i]['age'] >= 30) {
        array_splice($people, $i, 1);
    }
}
print_r($people);
Copy after login

Execute the above code and you will get the following output:

Array
(
    [0] => Array
        (
            [name] => 张三
            [age] => 25
        )

    [1] => Array
        (
            [name] => 王五
            [age] => 28
        )

)
Copy after login

You can see that the information of two people aged 30 or above has been were successfully deleted, while the information of two people younger than 30 years old remained unchanged.

3. Summary

In PHP, array is a very commonly used data structure. We can use various functions to add, delete, modify and check it. In this article, we introduce the replacement element operation of PHP arrays, focusing on the usage of the three functions array_replace(), array_replace_recursive() and array_splice(), and provide code examples based on specific application scenarios. I hope this article can help readers better understand and use the relevant knowledge of PHP arrays.

The above is the detailed content of Let's talk in depth about the replacement element operation of PHP arrays. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

What is the purpose of prepared statements in PHP? What is the purpose of prepared statements in PHP? Mar 20, 2025 pm 04:47 PM

Prepared statements in PHP enhance database security and efficiency by preventing SQL injection and improving query performance through compilation and reuse.Character count: 159

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

See all articles