Home > Article > Backend Development > How to delete the first element of an array in php
In PHP, sometimes we need to delete an array, and deleting the first element of the array is also one of the common requirements. Below we will introduce several methods to delete the first element of an array in PHP.
Method 1: Use the array_shift function
The array_shift function can be used to delete the first element in the array and return the deleted element. Here's how to use it:
$array = array('a', 'b', 'c'); $removed_element = array_shift($array); print_r($array); // 输出 ['b', 'c'] echo $removed_element; // 输出 'a'
Note that using the array_shift function to delete the first element of the array will cause the index of the array to be rearranged, which may cause performance problems. Additionally, the array_shift function returns null if the array is empty.
Method 2: Use the unset function
Another way to delete the first element of an array is to use the unset function. Here is how to use it:
$array = array('a', 'b', 'c'); unset($array[0]); print_r($array); // 输出 ['b', 'c']
Using the unset function to delete elements of the array will not affect the index of the array, nor will it affect the length of the array. If you want to remove multiple consecutive elements, you can use the array_splice function.
Method 3: Use array_slice function
array_slice function can return a certain slice of an array. If it is used to delete the first element of the array, we can intercept it from the second element to the end of the array. part. Here's how to use it:
$array = array('a', 'b', 'c'); $array = array_slice($array, 1); print_r($array); // 输出 ['b', 'c']
This method will also cause the array to rearrange its index, but has better performance than the array_shift function.
To sum up, the above are three methods to delete the first element of an array in PHP. Which method to use depends on actual needs and performance considerations. If you only need to delete one element and want to keep the index unchanged, it is recommended to use the unset function; if you need to keep the index but need to delete multiple elements, you can use the array_splice function; if you only need to delete one element and do not need to keep the index, it is recommended Use the array_shift function.
The above is the detailed content of How to delete the first element of an array in php. For more information, please follow other related articles on the PHP Chinese website!