Master PHP’s array_pop: Remove and Retrieve the Last Array Element

This article explains how PHP's array_pop() function removes the last element from an array, returns it, and demonstrates its usage with code examples, output interpretation, multiple-element removal, and important considerations for preserving the original array.

php Courses
php Courses
php Courses
Master PHP’s array_pop: Remove and Retrieve the Last Array Element

In PHP programming, array manipulation is common and often you need to take the last element from an array. The array_pop() function serves this purpose.

The array_pop() function pops the element at the end of an array and deletes it from the original array. It requires only the array as its argument. Below is a concrete code example and detailed explanation.

<?php
$fruits = array("apple", "banana", "orange", "grape");
$lastFruit = array_pop($fruits);
echo "弹出的元素是:" . $lastFruit . "
";
echo "剩余的数组是:";
print_r($fruits);
?>

The above code outputs:

弹出的元素是:grape
剩余的数组是:Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

In the example, we created an array named $fruits containing several fruit names, then used array_pop() to pop the last element and assign it to $lastFruit. Finally, we used 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 element "grape" has been successfully removed. This demonstrates the basic usage of array_pop().

If you need to delete multiple elements, you can call array_pop() repeatedly, each time removing one element, or use a loop to process each element for batch removal.

Note that using array_pop() modifies the original array structure. If you need to preserve the original array, copy it to a new variable first and then apply array_pop() on the copy.

In summary, array_pop() is a very practical PHP function for popping the last element of an array and removing it from the original array, which is useful in real-world development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendphp-functionsarray_pop
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.