Using array_pop() to Remove the Last Element from an Array in PHP
This article explains how PHP's array_pop() function removes the last element from an array, demonstrates its usage with a complete code example, shows the resulting output, and discusses best practices such as handling multiple removals and preserving the original array.
In PHP programming, array manipulation is very common and important. In practice we often need to retrieve the last element of an array, and the array_pop() function serves this purpose.
The array_pop() function removes the element at the end of an array and also deletes it from the original array. Its usage is straightforward: simply pass the array as the argument.
<?php
$fruits = array("apple", "banana", "orange", "grape");
$lastFruit = array_pop($fruits);
echo "弹出的元素是:" . $lastFruit . "\n";
echo "剩余的数组是:";
print_r($fruits);
?>The above code outputs:
弹出的元素是:grape
剩余的数组是:Array
(
[0] => apple
[1] => banana
[2] => orange
)In the example we create an array named $fruits containing several fruit names, then use array_pop() to pop the last element and assign it to the variable $lastFruit . Finally we use echo and print_r to display the popped element and the remaining array.
After calling array_pop() , the $fruits array contains only "apple", "banana" and "orange"; the "grape" element has been successfully removed.
If you need to delete multiple elements, you can call array_pop() repeatedly, each time removing one element, or use a loop structure to process each element in the array for batch removal.
Note that using array_pop() modifies the original array structure. If you need to keep the original elements, it is recommended to copy the array to a new variable before applying array_pop() .
In summary, array_pop() is a very useful PHP function for popping the last element of an array. It allows you to easily obtain the final element and remove it from the original array, which is valuable in real‑world development.
php8, I'm here
Scan the QR code to receive free learning materials
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.