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 code example that demonstrates defining an array of fruits, popping the final item, and displaying both the popped value and the remaining array contents.

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

In PHP we often need to manipulate array data; sometimes we need to retrieve the last element of an array.

The built-in array_pop function removes and returns the last element of an array.

Syntax: mixed array_pop ( array &$array ) If the array is empty the function returns null.

Example:

<?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);
?>

The script defines a $fruits array, uses array_pop to remove “grape”, stores it in $last_fruit, and prints both the removed value and the remaining array.

Running the code produces:

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

Summary

Using PHP’s array_pop makes it easy to pop and retrieve the last element of an array, a useful tool for array data handling.

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.

PHPphp-functionsarray 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.