How to Use PHP’s array_pop to Remove the Last Element from an Array

This article explains how PHP’s array_pop() function removes the last element from an array, provides a full code example with output, and discusses best practices such as handling multiple removals and preserving the original array.

php Courses
php Courses
php Courses
How to Use PHP’s array_pop to Remove the Last Element from an Array

In PHP programming, manipulating arrays is common, and extracting the last element often uses the array_pop() function.

The array_pop() function removes and returns the array’s last element. It takes the array as its sole argument. Below is a code example and detailed explanation.

<?php
$fruits = array("apple", "banana", "orange", "grape");
$lastFruit = array_pop($fruits);
echo "Popped element: " . $lastFruit . "
";
echo "Remaining array:
";
print_r($fruits);
?>

The above code outputs:

Popped element: grape
Remaining array: Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

In the example, we created an array $fruits with several fruit names, used array_pop() to pop the last element into $lastFruit, and then printed 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", 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 each element until the desired number of deletions 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 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.

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.

PHParray 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

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.