In PHP, array is a very commonly used data type. Sometimes we want to delete a key value in an array by key name. So in PHP, how to delete a key value by key name?
This article will share two methods, one is to use the unset() function, the other is to use the array_filter() function.
Method 1: Use the unset() function
The unset() function in PHP can be used to delete variables. When you use the unset() function to delete a key value in the array, the key value will be completely removed from the array.
The following is a code example of using the unset() function to delete a key value by key name:
$array = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ); // 使用unset()函数删除键名为'key2'的键值 unset($array['key2']); // 打印结果 print_r($array);
The execution results of the above code are as follows:
Array ( [key1] => value1 [key3] => value3 )
As you can see, using unset( ) function deletes the key value 'key2' in the array.
It should be noted that if the deleted key value does not exist, the unset() function will not throw any error and will not return any value.
Method 2: Use the array_filter() function
The array_filter() function can be used to filter arrays. When we want to delete a key value in the array, we can use the array_filter() function to filter out the key value with the specified value to achieve the deletion effect.
The following is a code example of using the array_filter() function to delete key values by key name:
$array = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', ); // 使用array_filter()函数过滤键名为'key2'的键值 $array = array_filter($array, function($key) { return $key != 'key2'; }, ARRAY_FILTER_USE_KEY); // 打印结果 print_r($array);
The execution results of the above code are as follows:
Array ( [key1] => value1 [key3] => value3 )
As you can see, using array_filter( ) function deletes the key value 'key2' in the array.
It should be noted that when using the array_filter() function to filter an array, you need to set the third parameter to ARRAY_FILTER_USE_KEY in order to filter the array based on the key name.
Conclusion
This article introduces two methods, using the unset() function and using the array_filter() function, to delete key values in the PHP array by key name. Both methods are very convenient and practical, and can be chosen according to the specific situation.
The above is the detailed content of How to delete key value by key name in php. For more information, please follow other related articles on the PHP Chinese website!