How to Use PHP’s array_pop to Remove the Last Element from an Array
Learn how PHP’s array_pop function removes and returns the last element of an array, with a clear syntax overview, step‑by‑step code example, and sample output illustrating the resulting array after popping the final item.
In PHP, the array_pop function is a convenient way to pop the last element off an array and return it.
Function Syntax
The function accepts a single argument – the array to be processed – and modifies the original array by removing its final element. If the array is empty, null is returned.
mixed array_pop ( array &$array )Example Usage
The following code defines an array of fruit names, uses array_pop to extract the last fruit, and then prints both the popped value 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);
?>Result
Running the script produces:
Popped element: grape
Remaining array:
Array
(
[0] => apple
[1] => banana
[2] => orange
)As shown, array_pop removed "grape" from the original array and returned it, leaving the array with the remaining fruit names.
Conclusion
The array_pop function is a simple yet powerful tool for handling array data in PHP, especially when you need to retrieve and discard the last element of a list.
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.
