Home > Article > Backend Development > How to delete the first key of an array in php
In PHP, you can use the unset() function to delete a single array element. However, for the first element of the array, we need to use the array_shift() function to successfully remove the element.
array_shift() is a very useful function that allows you to delete the first element in an array and returns the deleted element. However, note that one drawback of this function is that it will renumber the keys of the array so that the first element always has a key of 0.
Given the following code example, delete the first element of an array
<?php $myArray = array('one', 'two', 'three', 'four', 'five'); array_shift($myArray); print_r($myArray); ?>
In this example, we are using array_shift() function to delete the first element of $myArray and using print_r () function to view the contents of $myArray.
Output result:
Array ( [0] => two [1] => three [2] => four [3] => five )
You can see that the first key ‘one’ has been deleted and the keys of the array have been renumbered.
There is another way to delete the first element of the array, but it does not preserve the key number of the array. This method uses the array_slice() function to get a subarray of the array starting at index 1.
The following is a code example:
<?php $myArray = array('one', 'two', 'three', 'four', 'five'); $myArray = array_slice($myArray,1); print_r($myArray); ?>
In this example, we use the array_slice() function to get the subarray of the array starting from index 1, that is, starting from 'two', and The result is stored back into $myArray.
Output result:
Array ( [0] => two [1] => three [2] => four [3] => five )
Note that since the subarray is obtained starting from index 1, the keys of the array will not be renamed, but the extracted element will no longer be the first of the array element.
To delete any element in the array, you can use the unset() function, as shown in the following example:
<?php $myArray = array('one', 'two', 'three', 'four', 'five'); unset($myArray[2]); print_r($myArray); ?>
In this example, we use the unset() function to delete $myArray The third element (i.e. key 2), where the key value is 'three'.
Output result:
Array ( [0] => one [1] => two [3] => four [4] => five )
As you can see, another way to delete array elements is to use the unset() function. This method can delete any element in the array, but it cannot be used to delete the first element alone.
The above is the detailed content of How to delete the first key of an array in php. For more information, please follow other related articles on the PHP Chinese website!