How to Use PHP’s array_pop to Remove the Last Element from an Array
This guide explains PHP’s array_pop function, showing its syntax, behavior when the array is empty, and a complete example that pops the last fruit from an array, displays the removed element, and prints the remaining array contents.
Understanding PHP’s array_pop Function
PHP provides the array_pop function to remove and return the last element of an array. The function accepts a single array argument passed by reference; it modifies the original array and returns the removed value, or null if the array is empty.
Function Signature
mixed array_pop ( array &$array )Example Usage
The following script demonstrates defining an array of fruit names, using array_pop to extract the last fruit, and printing both the removed element and the remaining array.
<?php
// Define an array
$fruits = array("apple", "banana", "orange", "grape");
// Pop the last element
$last_fruit = array_pop($fruits);
// Output the popped element
echo "Popped element: " . $last_fruit . "
";
// Output the remaining array
echo "Remaining array:
";
print_r($fruits);
?>Running the script produces:
Popped element: grape
Remaining array:
Array
(
[0] => apple
[1] => banana
[2] => orange
)As shown, array_pop removes “grape” from the original array and returns it, leaving the array with the remaining fruit names.
Key Takeaway
Using array_pop is a simple and effective way to handle the last element of an array in PHP, especially when you need to both retrieve and delete that element.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
