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.
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);
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!