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.
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<br/>// Define an array<br/>$fruits = array("apple", "banana", "orange", "grape");<br/><br/>// Use array_pop to pop and return the last element<br/>$last_fruit = array_pop($fruits);<br/><br/>// Output the popped element<br/>echo "Popped element: " . $last_fruit . "<br/>";<br/><br/>// Output the remaining array<br/>echo "Remaining array:<br/>";<br/>print_r($fruits);<br/>?>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<br/>Remaining array:<br/>Array<br/>(<br/> [0] => apple<br/> [1] => banana<br/> [2] => orange<br/>)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
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
