Master PHP’s array_pop: Remove and Retrieve the Last Array Element
Learn how to use PHP’s built-in array_pop function to efficiently remove and return the last element of an array, with clear syntax explanation, a step-by-step code example, and expected output demonstrating its effect on the original array.
In PHP we often need to manipulate array data, and the built-in array_pop function provides a convenient way to pop the last element from an array.
The function’s syntax is: mixed array_pop ( array &$array ) It accepts an array by reference, removes the last element, and returns that element; if the array is empty it returns null.
Example:
<?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);
?>The script defines an array of fruit names, uses array_pop to remove “grape”, assigns it to $last_fruit, and prints both the popped value and the remaining array.
Running the code produces:
Popped element: grape
Remaining array:
Array
(
[0] => apple
[1] => banana
[2] => orange
)Summary
By using PHP’s array_pop function you can easily remove and retrieve the last element of an array, making it a useful tool for handling array data.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
