Using array_pop() to Remove the Last Element from a PHP Array
This article explains the PHP array_pop() function, demonstrating how it removes and returns the last element of an array, showing example code, output, and best practices such as handling multiple removals and preserving the original array when needed.
In PHP programming, array manipulation is common, and extracting the last element from an array is a frequent need.
The built‑in array_pop() function removes the element at the end of an array and returns it, requiring only the array variable as its argument.
Example code:
The script outputs the popped element “grape” and shows the remaining array containing “apple”, “banana”, and “orange”.
In the example, the $fruits array is created, array_pop() is called to assign the last element to $lastFruit, and echo and print_r display the results.
After calling array_pop() , $fruits contains only the first three fruits, confirming that the function has removed the last item.
To delete multiple elements, call array_pop() repeatedly or use a loop to pop elements until the desired count is reached.
Note that array_pop() modifies the original array; if the original data must be preserved, copy the array to another variable before popping.
In summary, array_pop() is a useful PHP function for retrieving and removing the last element of an array, simplifying common programming 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.