PHP
Create a Last-In, First-Out (LIFO) Stack with PHP Arrays
Learn to implement a basic stack data structure using standard PHP array functions like array_push and array_pop for LIFO operations.
<?php
class SimpleStack
{
private array $stack = [];
public function push(mixed $item): void
{
array_push($this->stack, $item);
echo "Pushed: " . (is_array($item) ? json_encode($item) : $item) . "
";
}
public function pop(): mixed
{
if ($this->isEmpty()) {
echo "Stack is empty, cannot pop.
";
return null;
}
$item = array_pop($this->stack);
echo "Popped: " . (is_array($item) ? json_encode($item) : $item) . "
";
return $item;
}
public function peek(): mixed
{
if ($this->isEmpty()) {
echo "Stack is empty, no item to peek.
";
return null;
}
$item = end($this->stack); // Get the last element without removing it
reset($this->stack); // Reset internal pointer
echo "Peeked: " . (is_array($item) ? json_encode($item) : $item) . "
";
return $item;
}
public function isEmpty(): bool
{
return empty($this->stack);
}
public function size(): int
{
return count($this->stack);
}
public function __toString(): string
{
return "Stack content: [" . implode(", ", array_map(function($item) {
return is_array($item) ? json_encode($item) : (string)$item;
}, $this->stack)) . "]
";
}
}
$stack = new SimpleStack();
$stack->push(10);
$stack->push('hello');
$stack->push(['user_id' => 123]);
echo $stack;
$stack->pop();
echo $stack;
$stack->peek();
echo $stack;
$stack->pop();
$stack->pop();
$stack->pop(); // Attempt to pop from an empty stack
echo $stack;
?>
How it works: This snippet demonstrates how to build a basic Last-In, First-Out (LIFO) stack using PHP arrays. It implements common stack operations like `push` (add to top), `pop` (remove from top), `peek` (view top), `isEmpty`, and `size`. This pattern is useful for managing execution flow, parsing, or undo/redo functionality.