Method: First use the array_search("key name",array_keys(array)) statement to obtain the corresponding key value in the array according to the specified key name; then use the "array_splice(array, key value, 1)" statement to delete Specify the key element.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
/** * php除数组指定的key值(直接删除key值实现) * @param unknown $data * @param unknown $key * @return unknown */ 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; }
Supplementary instructions:
array_search This function searches according to value and gets the position. If it cannot be found, it returns NULL or false; therefore, when searching for the position corresponding to the key by key, you need to find it in $keys. This is what calls array_keys. reason. Because the array_search function may return NULL or false, it must be used in absolute comparison.
Recommended: "2021 PHP interview questions summary (collection)" "php video tutorial》
The above is the detailed content of How to delete specified key from Array array in PHP. For more information, please follow other related articles on the PHP Chinese website!