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, demonstrates its syntax, provides a complete code example with output, and highlights its usefulness for backend array manipulation.
In PHP, handling array data often requires extracting the last element for further processing, and the built‑in array_pop function provides a convenient way to do this.
The function removes the final element from the given array and returns it, or returns null if the array is empty.
mixed array_pop ( array &$array )Below is a practical example that defines an array of fruit names, uses array_pop to pop 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 and return the last element
$last_fruit = array_pop($fruits);
// Output the popped element
echo "弹出的元素是:" . $last_fruit . "
";
// Output the remaining array
echo "剩余的数组是:
";
print_r($fruits);
?>Running the script produces the following output, showing that "grape" was removed and the remaining array contains the other three fruits.
弹出的元素是:grape
剩余的数组是:
Array
(
[0] => apple
[1] => banana
[2] => orange
)Thus, array_pop is a simple yet powerful tool for backend developers who need to manipulate array data efficiently.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.