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.
Now 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);
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, Return 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, so you have to compare absolutely, use! ==
Reference:
php official document: http://www.php100.com/cover/php/189.html
Welcome to join the PHP CodeIgniter community group: 460132647 Remarks: yanzi
The above introduces PHP to delete the specified key in the Array array (full version, encapsulated into a function, with test code attached), including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.