PHP deletes the specified key in the Array (full version, encapsulated as a function, with test code ). PHP deletes the specified key in the Array (full version, encapsulated as a function with test code). background: the key-value storage method in array is generally used, we sometimes need to delete the keys specified in the Array in PHP (full version, encapsulated as a function, with test code)
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! =
Background: the storage method of key-value in array is usually used. we sometimes need to delete it...