Home > Article > Backend Development > How to delete the key-value pair of specified k key in php
PHP is a commonly used server-side programming language, which can be used to develop various dynamic websites, Web applications and Web services. In the process of writing PHP programs, we often need to operate arrays, including adding, modifying, deleting elements, etc. This article will focus on how to delete specified key-value pairs in a PHP array.
You can use the unset function in PHP to delete specified elements in an array. The unset function can accept one or more parameters, each parameter represents an element. We only need to pass the key name of the element to be deleted as a parameter to delete the element. The example is as follows:
<?php // 定义一个关联数组 $arr = array('name'=>'Tom', 'age'=>20, 'gender'=>'male'); // 删除gender项 unset($arr['gender']); print_r($arr); // 输出结果:Array([name] => Tom [age] => 20) ?>
The array_splice function can also be used in PHP Delete the value of the specified key. This function removes elements from an array, rearranges the array, and returns an array containing the removed elements. If we want to retain the element's position in the array after deleting it, we can replace the element with null. An example is as follows:
<?php // 定义一个关联数组 $arr = array('name'=>'Tom', 'age'=>20, 'gender'=>'male'); // 删除gender项 array_splice($arr,array_keys($arr,array_search('male',$arr)),1); print_r($arr); // 输出结果:Array([name] => Tom [age] => 20) ?>
If we want to delete the specified key-value pairs in the array and keep the remaining elements, we can use the array_filter function. The array_filter function can accept an array as a parameter, filter the array elements according to the specified callback function, and return a new array. We only need to write a callback function and exclude the specified elements in the callback function. Examples are as follows:
<?php // 定义一个关联数组 $arr = array('name'=>'Tom', 'age'=>20, 'gender'=>'male'); // 删除gender项 $arr = array_filter($arr, function($key){ return $key != 'gender';}, ARRAY_FILTER_USE_KEY); print_r($arr); // 输出结果:Array([name] => Tom [age] => 20) ?>
The above are three methods of deleting specified key-value pairs in PHP. Each method is different. We can choose the appropriate method according to specific needs.
The above is the detailed content of How to delete the key-value pair of specified k key in php. For more information, please follow other related articles on the PHP Chinese website!