Using PHP's array_pop to Remove and Return the Last Element of 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, and shows the resulting output, helping developers efficiently manipulate array data in backend applications.
In PHP, the array_pop function is a convenient built‑in utility for popping the last element off an array and returning it.
The function signature is:
mixed array_pop ( array &$array )If the array is empty, the function returns null . It modifies the original array by removing its final element.
Below is a full example that defines an array of fruit names, uses array_pop to extract 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 this 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 provides a simple way to handle the last element of an array, which is especially useful in backend data‑processing tasks.
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.