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 expected output, and highlights its usefulness for array manipulation in backend development.
In PHP we often need to manipulate array data, and sometimes we need to extract the last element for further processing. PHP offers a convenient built‑in function called array_pop for this purpose.
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 by reference, removes the final element, and returns that element; if the array is empty it returns null .
Below is a practical example that demonstrates how to use array_pop :
<?php
// Define an array
$fruits = array("apple", "banana", "orange", "grape");
// Pop the last element and store it
$last_fruit = array_pop($fruits);
// Output the popped element
echo "Popped element: " . $last_fruit . "\n";
// Output the remaining array
echo "Remaining array:\n";
print_r($fruits);
?>The code creates an array named $fruits containing several fruit names, uses array_pop to remove the last element ( grape ), assigns it to $last_fruit , and prints it. It then prints the remaining array.
If you run the script, the output will be:
Popped element: grape
Remaining array:
Array
(
[0] => apple
[1] => banana
[2] => orange
)As shown, array_pop successfully extracts the final element ( grape ) and leaves the rest of the array intact.
Summary
By using PHP's array_pop function, you can easily pop and retrieve the last element of an array, a handy tool for array manipulation in backend development.
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.