Home > Backend Development > PHP Problem > How to delete specified key from Array array in PHP

How to delete specified key from Array array in PHP

醉折花枝作酒筹
Release: 2023-03-09 11:34:02
Original
2336 people have browsed it

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.

How to delete specified key from Array array in PHP

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template