Home > Backend Development > PHP Problem > How to delete specified key in php

How to delete specified key in php

藏色散人
Release: 2023-03-02 21:14:01
Original
3873 people have browsed it

php method to delete the specified key: first use the "array_search" function to search according to the value; then press the key to find the location corresponding to the key; finally use the customized "array_remove" method to delete the specified key.

How to delete specified key in php

PHP deletes the specified key in the Array array (full version, encapsulated into a function, with test code attached)

Problem background: Arrays are generally stored in key-value storage. Sometimes we need to delete the specified key and corresponding value. But I don’t know why, so many posts are talking about knowing the value and deleting the value, which almost misled me.

Recommendation: "PHP Tutorial"

Now I attach the complete version of the code I wrote:

function array_remove($data, $key){
    if(!array_key_exists($key, $data)){
        return $data;
    }
    $keys = array_keys($data);
    $index = array_search($key, $keys);
    if($index !== FALSE){
        array_splice($data, $index, 1);
    }
    return $data;
 
}
$data = array('name'=>'apple','age'=>12,'address'=>'ChinaGuangZhou');
$result = array_remove($data, 'name');
var_dump($result);
Copy after login

Supplementary instructions:

1. In fact, the problem lies in the array_search function. This function searches according to the value and gets the position. If it cannot find it, it returns NULL or false;

2. Therefore, when searching for the key corresponding to the key, When searching for the location, you need to find it in $keys. This is the reason for calling array_keys

3. Because the array_search function may return NULL or false, you must use absolute comparison!

The above is the detailed content of How to delete specified key in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template