Backend Development 4 min read

Using PHP's array_pop() to Remove the Last Element from an Array

This article explains how the PHP array_pop() function removes and returns the last element of an array, demonstrates its usage with a fruit array example, shows the resulting output, and discusses considerations such as multiple removals, looping, and preserving the original array.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_pop() to Remove the Last Element from an Array

In PHP programming, array manipulation is common, and extracting the last element of an array is a frequent task; 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.

<?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 $fruits containing several fruit names, use array_pop() to remove the last element, assign it to $lastFruit , and then print both the popped element and the remaining array using echo and print_r .

After calling array_pop() , the $fruits array contains only "apple", "banana", and "orange"; the "grape" element has been successfully removed, illustrating 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 each element until the desired number of removals is reached.

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 practical PHP function for popping the last element of an array, allowing developers to easily retrieve and remove that element, which is useful in many programming scenarios.

backendPHPTutorialFunctionsarray-manipulationarray_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

login 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.