PHP
Implement a Basic Stack Using PHP Arrays
Learn how to use standard PHP array functions to create and manage a Last-In, First-Out (LIFO) stack data structure for various applications.
<?php
// Initialize an empty array to serve as our stack
$stack = [];
// Push elements onto the stack (LIFO: Last-In, First-Out)
array_push($stack, 'item1');
array_push($stack, 'item2');
array_push($stack, 'item3');
// echo "Current stack: " . implode(', ', $stack) . "
";
// Expected: item1, item2, item3
// Pop elements from the stack
$lastItem = array_pop($stack); // $lastItem will be 'item3'
// echo "Popped: " . $lastItem . "
";
// echo "Stack after pop: " . implode(', ', $stack) . "
";
// Expected: item1, item2
$secondLastItem = array_pop($stack); // $secondLastItem will be 'item2'
// echo "Popped: " . $secondLastItem . "
";
// echo "Stack after pop: " . implode(', ', $stack) . "
";
// Expected: item1
// Check if the stack is empty
if (empty($stack)) {
// echo "Stack is now empty.
";
}
// You can also add elements directly using array syntax
$stack[] = 'new_item'; // equivalent to array_push($stack, 'new_item');
// echo "Stack after direct add: " . implode(', ', $stack) . "
";
// Expected: item1, new_item
// Get the top element without removing it (peek)
$topItem = end($stack); // 'new_item'
// reset($stack); // Always call reset after end() if you intend to iterate or use other array pointers
// echo "Top item (peek): " . $topItem . "
";
How it works: This snippet demonstrates how to simulate a Last-In, First-Out (LIFO) stack data structure using standard PHP array functions. `array_push()` is used to add elements to the "top" of the stack, and `array_pop()` removes and returns the element from the "top." This simple implementation is effective for managing sequences where the most recently added item is the first one to be processed or retrieved, such as tracking history or undo operations.