Home >Backend Development >PHP Problem >php delete array last
In PHP, there are many ways to delete the last element of an array. Let’s explore a few common methods below.
The array_pop function removes and returns the last element of an array. On this basis, we can delete the last element through the following code:
$array = array(1, 2, 3, 4, 5); array_pop($array); print_r($array); // 输出 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Through this method, the last element can be deleted directly, but the value of the last element cannot be obtained while deleting.
Use the unset function to delete elements based on the array subscript. We can delete the last element of the array through the following code:
$array = array(1, 2, 3, 4, 5); unset($array[count($array) - 1]); print_r($array); // 输出 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Among them, the count function is used to get the length of the array (that is, the number of elements), and get the subscript of the last element by subtracting 1. However, this method cannot obtain the value of the last element while deleting.
The array_splice function can remove elements from an array and return the cut elements. We can delete the last element of the array through the following code:
$array = array(1, 2, 3, 4, 5); array_splice($array, -1); print_r($array); // 输出 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Among them, -1 means starting from the last element of the array. Use this method to simultaneously delete the last element and get its value.
The array_slice function can return a slice from an array. We can obtain all elements of the array except the last element through the following code:
$array = array(1, 2, 3, 4, 5); $array = array_slice($array, 0, -1); print_r($array); // 输出 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Among them, the first parameter indicates the array to be sliced, the second parameter indicates the starting position to be cut, and the third parameter The parameter indicates the length to be cut. We set the second parameter to 0, which starts cutting from the first element of the array, and the third parameter to -1, which ends cutting from the last element of the array. This method can get all elements except the last element. If you want to delete the last element directly, you can assign the result returned by this method to the original array variable.
To sum up, the above is the method to delete the last element of the array in PHP. We can choose different methods to delete or get the last element of the array according to different situations.
The above is the detailed content of php delete array last. For more information, please follow other related articles on the PHP Chinese website!