PHP
π€ PHP array_pop() Function: Removing the Last Element
The array_pop() function in PHP removes and returns the last element off the end of an array. It shortens the target array by one element and resets array pointers.
-
Return Value:
array_pop()returns the removed value. If the array is empty, it returnsnull.
π οΈ Basic Syntax & Usage
Pass an array variable to array_pop() to strip its final value:
PHP
$stack = ["HTML", "CSS", "JavaScript", "PHP"];
// Pop the last element off the end
$lastItem = array_pop($stack);
echo "Popped Element: " . $lastItem; // Outputs: Popped Element: PHP
print_r($stack);
/*
Output:
Array
(
[0] => HTML
[1] => CSS
[2] => JavaScript
)
*/
π Stack (LIFO) Operations with PHP
Combining array_push() and array_pop() allows you to easily implement a standard Last-In, First-Out (LIFO) stack data structure in PHP.
PHP
$actions = [];
// Push items onto stack
array_push($actions, "Page 1");
array_push($actions, "Page 2");
// Undo action (Pop last item)
$previousPage = array_pop($actions); // "Page 2"
echo "Current Page: " . end($actions); // Outputs: Page 1
π Key Rules & Behaviors
-
1. Direct Mutation: Like
array_push(),array_pop()modifies the source array directly by reference. - 2. Indexing Behavior: Numeric keys are re-indexed consecutively, while associative string keys are cleanly removed without affecting other key pairs.
-
3. Empty Array Handling: Calling
array_pop()on an empty array silently returnsnullwithout raising an error.
π Array End Stack Operations Comparison
| Function | Action | Target Position | Return Value |
|---|---|---|---|
array_push() |
Adds element(s) | End of array | New total element count |
array_pop() |
Removes element | End of array | The removed element value (or null) |
-
π Short Summary
-
array_pop()extracts and removes the final element from an array. - It directly modifies the source array variable passed into the function.
-
Use
array_pop()in combination witharray_push()to build LIFO stacks.
