: This article describes how to delete the specified key in the Array in PHP (full version, encapsulated as a function with test code). For more information about PHP tutorials, see. Problem background: the storage method of key-value in array is usually used. we sometimes need to delete the specified key and the corresponding value. But I don't know why, so many posts are about knowing the value and deleting the value, almost misleading me.
The full version code I wrote is now included:
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);
Note:
1. in fact, the problem lies in the array_search function. this function searches by value to obtain the location. if it cannot be found, NULL or false is returned;
2. Therefore, you need to find the corresponding location of the key in $ keys, which is the reason for calling array_keys.
3. because the array_search function may return NULL and false, you must use absolute comparison! =
Refer:
Php official documentation: http://www.php100.com/cover/php/189.html
Welcome to the PHP CodeIgniter community group: 460132647 remarks: yanzi
The preceding section describes how to delete the specified key in the Array in PHP (full version, encapsulated as a function with test code), including the following content, if you are interested in PHP tutorials.