In PHP, you can use the array_pop() function to delete the last element in an array. This function returns the deleted element.
Sample code:
$myArray = [1, 2, 3, 4, 5]; $lastElement = array_pop($myArray); echo "被删除的元素是:" . $lastElement . "<br>"; print_r($myArray);
The output result is:
被删除的元素是:5 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
In the above example, we created an array containing 5 elements$myArray
, and then use the array_pop()
function to delete the last element 5 and assign it to the variable $lastElement
. Finally, the print_r()
function is used to output the array $myArray
with the last element removed.
In addition to using the array_pop()
function, you can also use the unset()
function to set the last element in the array to NULL or delete the element:
$myArray = [1, 2, 3, 4, 5]; unset($myArray[count($myArray) - 1]); print_r($myArray);
The above code uses the unset()
function to delete the last element 5 in the array and output the remaining elements.
No matter which deletion method is used, remember to ensure that the key values of the array are still continuous after deleting an array element.
The above is the detailed content of How to delete the last element of an array in PHP. For more information, please follow other related articles on the PHP Chinese website!