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