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

Learn how PHP’s array_pop function removes and returns the last element of an array, with a clear syntax overview, step‑by‑step code example, and sample output illustrating the resulting array after popping the final item.

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

In PHP, the array_pop function is a convenient way to pop the last element off an array and return it.

Function Syntax

The function accepts a single argument – the array to be processed – and modifies the original array by removing its final element. If the array is empty, null is returned.

mixed array_pop ( array &$array )

Example Usage

The following code defines an array of fruit names, uses array_pop to extract the last fruit, and then prints both the popped value and the remaining array.

<?php
// Define an array
$fruits = array("apple", "banana", "orange", "grape");

// Pop the last element
$last_fruit = array_pop($fruits);

// Output the popped element
echo "Popped element: " . $last_fruit . "
";

// Output the remaining array
echo "Remaining array:
";
print_r($fruits);
?>

Result

Running the script produces:

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

As shown, array_pop removed "grape" from the original array and returned it, leaving the array with the remaining fruit names.

Conclusion

The array_pop function is a simple yet powerful tool for handling array data in PHP, especially when you need to retrieve and discard the last element of a list.

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.

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