problem background: Array is generally key---value storage, we sometimes need to delete the specified key and corresponding value. But I do not know why, so many of the posts are talking about knowing the value, and delete the value of things, almost misled me.
Now I am writing the full version of the Code attached:
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 notes:
1, in fact, the problem is array_search this function, the function according to value to search, get the position, if not found on the return null or false;
2, therefore, in the key to find the corresponding position of key, need to find in the $keys, this is the reason to call Array_keys
3, because array_search this function may return null and false, so the absolute comparison must be used! = =
Reference:
PHP Official Document: http://www.php100.com/cover/php/189.html
Welcome to join PHP CodeIgniter community Group: 460132647 Remarks: Yanzi
The above describes the PHP delete array in the specified key (full version, has been encapsulated into functions, with test code), including the aspects of the content, I hope to be interested in PHP tutorial friends helpful.