Home  >  Article  >  Backend Development  >  How to delete specified keys in php array

How to delete specified keys in php array

藏色散人
藏色散人Original
2020-07-08 09:12:433445browse

php method to delete the specified key of the array: first create a PHP code sample file; then define an "array_remove" method; finally use "array_key_exists", "array_search" and other functions to delete the specified key of the array.

How to delete specified keys in php array

PHP deletes the key specified in the Array array

/**
 * 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;
 
}
 
/**
 * php除数组指定的key值(通过直接重新组装一个数组)
 * @param unknown $data
 * @param unknown $key
 * @return unknown
 */
function array_remove1($data,$delKey) {
$newArray = array();
if(is_array($data)) {
foreach($data as $key => $value) {
if($key !== $delKey) {
$newArray[$key] = $value;
}
}
}else {
$newArray = $data;
}
return $newArray;
}
 
$data = array('apple','address','ChinaGuangZhou');
$result = array_remove($data, 'name');
$result1 = array_remove1($data, 'name');
print_r($result);
print_r($result1);

Supplementary instructions:

1, In fact, the problem lies in the array_search function. This function searches according to value and gets the position. If it cannot find it, it returns NULL or false;

2. Therefore, when searching for the position 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 or false, you must use absolute comparison!

For more related knowledge, please visit PHP Chinese website!

The above is the detailed content of How to delete specified keys in php array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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