Using PHP’s array_pop Function to Remove the Last Element from an Array
This article explains how PHP’s built‑in array_pop function removes and returns the last element of an array, demonstrates its syntax, provides a complete code example that pops a fruit from a list, and shows the resulting output and remaining array contents.
In PHP we often need to handle array data. Sometimes we need to take the last element from an array and operate on it. PHP provides a very convenient function for this purpose, the “array_pop” function.
“array_pop” function is used to pop and return the last element from an array. Its syntax is as follows: mixed array_pop ( array &$array ) The function accepts an array as a parameter, removes the last element from the array, and returns that element. If the array is empty, it returns null.
Next, let's look at a code example that uses the “array_pop” function:
<?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/>?><br/>The code defines an array named “fruits” containing several fruit names, uses “array_pop” to pop the last element, assigns it to the variable “$last_fruit”, and prints it. It then prints the remaining array using print_r.
If you run the above code, you will get the following output:
弹出的元素是:grape<br/>剩余的数组是:<br/>Array<br/>(<br/> [0] => apple<br/> [1] => banana<br/> [2] => orange<br/>)<br/>As you can see, the “array_pop” function popped the last element “grape” from the array and returned it. The remaining array contains only the remaining fruit names.
Summary
By using PHP's “array_pop” function, we can easily pop and return the last element of an array. This function is very useful for handling array data. Hope this article helps you!
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.
