Home >Backend Development >PHP Problem >How to delete the key value of an array in php
In PHP, array is a very important data type. Sometimes, we need to delete an element of an array instead of just changing its value. To delete an element from an array, use the unset() function. This function is used to release the memory of the specified variable and set it to null.
Here's how to delete the key value of an array in PHP:
If you want to delete the specified element in an array , you can use the unset() function and provide the key value of the element to be deleted as a parameter. For example, if you want to delete the "apple" element in the array below, you can write the code like this:
$array = array("apple", "banana", "orange"); unset($array[0]);
In the above example, the unset() function will delete the "apple" element in the array and replace it with Array reindexing. After executing the above code, the result of the array is as follows:
array(2) { [1]=> string(6) "banana" [2]=> string(6) "orange" }
If you want to delete all elements in the array, you can use unset() function and pass in the key values of all elements. For example, if you have an associative array, you can write the code like this:
$array = array("name" => "John", "age" => 30, "city" => "New York"); foreach(array_keys($array) as $key){ unset($array[$key]); }
In the above example, the unset() function will remove all elements in the array and reset the array to an empty array. If you execute var_dump($array), you will see the following output:
array(0) { }
Sometimes, you may want to delete the last element in the array an element. In this case you can use array_pop() function. This function pops an element from the end of the array and returns it. For example, if you have a numerically indexed array, you can write the code like this:
$array = array("apple", "banana", "orange"); $last_element = array_pop($array);
In the above example, the array_pop() function will return "orange", changing the value of $array to array("apple ", "banana").
If you want to delete the first element in the array, you can use the array_shift() function. This function removes an element from the head of the array and returns it. For example, if you have a numerically indexed array, you could write the code like this:
$array = array("apple", "banana", "orange"); $first_element = array_shift($array);
In the above example, the array_shift() function will return "apple", changing the value of $array to array("banana ", "orange").
Deleting elements of an array is a very basic operation in PHP. Whether your array is numerically indexed or associative, you can use the unset(), array_pop(), and array_shift() functions to remove its elements.
The above is the detailed content of How to delete the key value of an array in php. For more information, please follow other related articles on the PHP Chinese website!