Backend Development 4 min read

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, provides its syntax, demonstrates its usage with a complete code example, shows the resulting output, and highlights its usefulness for array manipulation 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 process array data, and sometimes we need to extract the last element for further operations. PHP offers a very convenient function for this purpose called array_pop .

The array_pop function removes and returns the last element of an array. Its syntax is:

mixed array_pop ( array &$array )

The function accepts an array as its argument, removes the final element from that array, and returns the removed element; if the array is empty, it returns null .

Below is a code example that uses array_pop :

<?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: " . $last_fruit . "
";
// Output the remaining array
echo "Remaining array:
";
print_r($fruits);
?>

The code defines an array named fruits containing several fruit names, then uses array_pop to remove the last element ( grape ) and assigns it to $last_fruit , which is printed. Afterwards, print_r displays the remaining elements of the array.

If you run the code, the output will be:

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

As shown, array_pop successfully removes the final element ( grape ) from the array and returns 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, which is very useful for handling array data in backend development.

Java learning material download

C language learning material download

Frontend learning material download

C++ learning material download

PHP learning material download

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

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