Master PHP’s array_pop: Quickly Remove the Last Element from an Array
This tutorial explains how the PHP function array_pop() removes and returns the last element of an array, demonstrates its usage with clear code examples, and discusses best practices such as preserving the original array and removing multiple elements.
In PHP programming, array operations are common, and extracting the last element of an array is often needed. The array_pop() function serves this purpose.
The array_pop() function removes and returns the array’s last element. It requires only the array as its argument. Below is a concrete example.
<?php
$fruits = array("apple", "banana", "orange", "grape");
$lastFruit = array_pop($fruits);
echo "Popped element: " . $lastFruit . "
";
echo "Remaining array:
";
print_r($fruits);
?>The code above outputs:
Popped element: grape
Remaining array: Array
(
[0] => apple
[1] => banana
[2] => orange
)In the example, we created an array $fruits containing several fruit names, used array_pop() to pop the last element into $lastFruit, and then displayed the popped element and the remaining array with echo and print_r.
After calling array_pop(), the $fruits array contains only "apple", "banana", and "orange", while "grape" has been removed. This demonstrates the basic usage of array_pop().
If you need to delete multiple elements, you can call array_pop() repeatedly or use a loop to pop elements until the desired number is removed.
Note that array_pop() modifies the original array. To preserve the original data, copy the array to a new variable before applying array_pop().
In summary, array_pop() is a handy PHP function for popping the last element of an array and removing it from the original array, which is useful in many programming scenarios.
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.
