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

Learn how to use PHP’s built-in array_pop function to efficiently remove and return the last element of an array, with clear syntax explanation, a step-by-step code example, and expected output demonstrating its effect on the original array.

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

In PHP we often need to manipulate array data, and the built-in array_pop function provides a convenient way to pop the last element from an array.

The function’s syntax is: mixed array_pop ( array &$array ) It accepts an array by reference, removes the last element, and returns that element; if the array is empty it 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 an array of fruit names, uses array_pop to remove “grape”, assigns it to $last_fruit, and prints both the popped value and the remaining array.

Running the code produces:

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

Summary

By using PHP’s array_pop function you can easily remove and retrieve the last element of an array, making it a useful tool for handling array data.

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.

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