Home Backend Development PHP Problem How to delete elements by value in php two-dimensional array

How to delete elements by value in php two-dimensional array

Apr 27, 2023 am 09:08 AM

In PHP, arrays are a very common data structure, among which two-dimensional arrays are even more commonly used. However, when using a two-dimensional array, sometimes we need to delete an element in it. At this time, we need to consider deleting the element by value. This article will introduce how to delete elements from a two-dimensional array by value in PHP.

1. Use foreach loop to delete elements

The simplest way to delete elements by value in a two-dimensional array is to use a foreach loop to traverse the array, and then determine whether each element in the array is equal to The value we want to delete, if equal, delete the element. The code is as follows:

$arr = array(
    array('name' => '张三', 'age' => 18),
    array('name' => '李四', 'age' => 20),
    array('name' => '王五', 'age' => 22),
);

foreach ($arr as $k => $v) {
    if ($v['name'] == '李四') {
        unset($arr[$k]);
    }
}
Copy after login

In the above code, we first define a two-dimensional array $arr, and then use a foreach loop to traverse the array to determine the "name" of each element in the array "Whether the key is equal to "John Doe", if so, use the unset() function to delete the element from the array. The final array will not contain the element "John Doe".

It should be noted that when using the unset() function to delete elements, you must use $k as the key name instead of $v, otherwise an error will occur.

2. Use the array_filter function to delete elements

Another way to delete elements in a two-dimensional array by value is to use the array_filter function, which can use a callback function for each element in the array Filters the elements and returns a new array that does not contain the filtered elements. The code is as follows:

$arr = array(
    array('name' => '张三', 'age' => 18),
    array('name' => '李四', 'age' => 20),
    array('name' => '王五', 'age' => 22),
);

$arr = array_filter($arr, function($v) {
    return $v['name'] != '李四';
});
Copy after login

In the above code, we pass the callback function as the second parameter to the array_filter function. The callback function accepts each element in the array as a parameter and returns a Boolean value. If it returns true, it means that the element will be retained in the new array, if it returns false, it means that the element will be removed from the new array.

In the above code, we use an anonymous function as a callback function to determine whether the "name" key of each element is equal to "李思". If not, return true, indicating that the element will be retained in in the new array, otherwise false is returned, indicating that the element will be deleted from the new array.

It should be noted that the array_filter function will return a new array, so we need to save the returned array to the original array to obtain the final array with the specified elements deleted.

3. Use the array_search function to delete elements

Another way to delete elements in a two-dimensional array by value is to use the array_search function, which can be used to find the key of a specified value in an array , and returns its key name. The code is as follows:

$arr = array(
    array('name' => '张三', 'age' => 18),
    array('name' => '李四', 'age' => 20),
    array('name' => '王五', 'age' => 22),
);

$key = array_search('李四', array_column($arr, 'name'));

if ($key !== false) {
    unset($arr[$key]);
}
Copy after login

In the above code, we use the array_search function to find the key of '李思' in the array. This function accepts two parameters. The first parameter is the value to be found, and the second The first parameter is the array to search for. In the above code, we extract the two-dimensional array into a one-dimensional array by column, and then search for the key name of '李思' in the one-dimensional array. Once the key name is found, we use the unset() function to unset the element corresponding to the key. delete.

It should be noted that the array_search function returns the key name of the search result. If the search fails, it returns false. We need to use the !== operator to check whether the return value is false. If not, it means that the search is successful and the specified element can be deleted. Otherwise, the specified element cannot be found.

Summary

There are many ways to delete two-dimensional array elements by value. The above introduces three common methods:

Use a foreach loop to traverse the array and determine each Whether the value of the element is equal to the value to be deleted, if so, use the unset() function to delete the element.

Use the array_filter function to filter the array, and use the callback function to determine whether each element needs to be retained in the new array.

Use the array_search function to find the key with the specified value in the array, and then use the unset() function to delete the element corresponding to the key.

In actual development, we can choose different methods to delete array elements according to specific needs to achieve optimal performance and efficiency.

The above is the detailed content of How to delete elements by value in php two-dimensional array. 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 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.

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 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.

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.

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 mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

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

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

See all articles