Home >Backend Development >PHP Tutorial >PHP deletes the specified key in the Array array (full version, encapsulated into a function, with test code attached)_PHP tutorial

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

WBOY
WBOYOriginal
2016-07-12 09:04:21910browse

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

Problem background: Arrays generally use key-value storage methods. 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.

Attached is 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);

Additional 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 be found, it returns NULL or false;

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

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1073357.htmlTechArticlePHP deletes the specified key in the Array array (full version, encapsulated into a function, with test code attached) Problem background: Array is generally a key-value storage method. Sometimes we need to delete...
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