Home > Article > Backend Development > How to delete key-value pairs in an array in php
In PHP, array is a very useful data type, which allows us to combine multiple values to find and operate easily. Sometimes, we need to delete a key-value pair (that is, a key and the corresponding value) from an existing array. In this case, we can use some of the functions that come with PHP to complete this operation.
Let’s take a look at how to delete key-value pairs in a PHP array. First, we can use the unset() function to delete the value of a specified key. Here is an example:
$fruit = array( 'apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange' ); unset($fruit['banana']); print_r($fruit);
Output:
Array ( [apple] => red [orange] => orange )
As mentioned above, we used the unset() function to delete the key-value pair with the key 'banana' in the array $fruit. When we print the $fruit array again, we can see that 'banana' is no longer in it.
Another way to delete multiple key-value pairs in an array is to use the array_diff_key() function. The array_diff_key() function compares the keys of two or more arrays and returns a new array containing the key differences. We can remove key-value pairs by merging this array with the original array. The following is an example:
$fruit = array( 'apple' => 'red', 'banana' => 'yellow', 'orange' => 'orange' ); $to_remove = array( 'banana' => true, 'orange' => true ); $fruit = array_diff_key($fruit, $to_remove); print_r($fruit);
Output:
Array ( [apple] => red )
In the above example, we first create a new array $to_remove, which contains the key names to be deleted. We then use the array_diff_key() function to compare the $fruit array with the $to_remove array to get a new array containing only the keys that exist in the $fruit array. Finally, we assign this new array to $fruit and complete the deletion operation.
It should be noted that using the unset() function will directly modify the original array, while using the array_diff_key() function will create a new array, so when multiple key-value pairs need to be deleted, especially for For large arrays, it is more efficient to use array_diff_key().
To summarize, there are two common ways to delete key-value pairs in PHP arrays: using the unset() function and the array_diff_key() function. When using the unset() function, you only need to specify the key name you want to delete. When using the array_diff_key() function, you need to create a new array containing the key names to be deleted, and compare the two arrays to obtain a new array to achieve deletion. It is necessary to flexibly choose different deletion methods according to the actual situation to achieve more efficient and convenient operations.
The above is the detailed content of How to delete key-value pairs in an array in php. For more information, please follow other related articles on the PHP Chinese website!