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

This article explains how PHP's array_pop function removes and returns the last element of an array, shows its syntax, provides a complete code example with expected output, and summarizes its usefulness for handling array data in backend development.

php Courses
php Courses
php Courses
Using PHP's array_pop Function to Remove the Last Element from an Array

In PHP we often need to manipulate array data, and sometimes we need to extract the last element for further processing. PHP provides a very convenient function for this purpose, called the array_pop function.

The array_pop function removes and returns the last element of an array. Its syntax is as follows: mixed array_pop ( array &$array ) This function accepts an array as its argument, removes the last element from that array, and returns the element. If the array is empty, it returns null.

Next, we look at a code example that uses the array_pop function:

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

// Use array_pop to pop and return the last element
$last_fruit = array_pop($fruits);

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

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

The code defines an array named fruits containing several fruit names, then uses array_pop to pop the last element, assigns it to $last_fruit, and prints it. Afterwards it prints the remaining array using print_r.

If you run the above code you will get the following output:

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

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

Summary

By using PHP's array_pop function, we can easily pop and return the last element of an array. This function is very useful for handling array data. Hope this article helps you!

PHP Practical Development Fast-Track

Scan the QR code to receive free learning materials

QR code
QR code
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.

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