$v){if($k=='specified value'){$arr[$k]='';}}"."/> $v){if($k=='specified value'){$arr[$k]='';}}".">

Home >Backend Development >PHP Problem >How to delete array elements in php while retaining keys

How to delete array elements in php while retaining keys

青灯夜游
青灯夜游Original
2021-07-08 13:52:331853browse

In PHP, you can use foreach to traverse the array, find the element with the specified key name through the if statement, and set the key value of the key name to empty to achieve the effect of deleting the array element and retaining the key; the syntax "foreach($ arr as $k=>$v){if($k=='specified value'){$arr[$k]='';}}".

How to delete array elements in php while retaining keys

The operating environment of this tutorial: Windows 7 system, PHP version 7.1, DELL G3 computer

php deletes array elements to retain keys

Create a new PHP file named test.php to explain how PHP deletes the key values ​​in the array and retains the key name.

How to delete array elements in php while retaining keys

In the test.php file, use the header() method to set the encoding format of the page to utf-8.

How to delete array elements in php while retaining keys

In the test.php file, define an associative array for testing.

How to delete array elements in php while retaining keys

In the test.php file, use foreach to traverse the array, find the key value with the key name of the letter c through the if statement, and set the key value of the key name to If empty, you can delete the key value in the array and retain the key name.

How to delete array elements in php while retaining keys

In the test.php file, use print_r to output the changed array.

How to delete array elements in php while retaining keys

Open the test.php file in the browser to view the results.

How to delete array elements in php while retaining keys

Recommended study: "PHP Video Tutorial"

The above is the detailed content of How to delete array elements in php while retaining keys. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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