Stack Using Array in DSA – Implementation, Operations & PHP Code
📘 Stack Using Array
🚀 Introduction
A Stack is a linear data structure that follows:
👉 LIFO (Last In, First Out)
In this approach, we implement a stack using an array, where the last element represents the top of the stack.
🔹 Stack Representation
Top → [30, 20, 10]
👉 Here:
- 30 is the top element
- 10 is the bottom element
🔹 Basic Operations
1️⃣ Push
Adds an element to the top.
2️⃣ Pop
Removes the top element.
3️⃣ Peek
Returns the top element.
4️⃣ isEmpty
Checks if stack is empty.
🔹 Algorithm
✔️ Push Operation
- Check if stack is full (optional in dynamic array)
- Add element to array
- Update top
✔️ Pop Operation
- Check if stack is empty
- Remove last element
- Return value
🧑💻 PHP Implementation
<?phpclass Stack {
private $stack = [];
private $size; public function __construct($size = 10) {
$this->size = $size;
} // Push operation
public function push($value) {
if (count($this->stack) >= $this->size) {
return "Stack Overflow";
} $this->stack[] = $value;
return "Inserted: $value";
} // Pop operation
public function pop() {
if (empty($this->stack)) {
return "Stack Underflow";
} return array_pop($this->stack);
} // Peek operation
public function peek() {
if (empty($this->stack)) {
return "Stack is Empty";
} return end($this->stack);
} // isEmpty
public function isEmpty() {
return empty($this->stack);
} // Display stack
public function display() {
echo "Stack: ";
foreach (array_reverse($this->stack) as $val) {
echo $val . " ";
}
}
}// Example
$stack = new Stack(5);echo $stack->push(10) . "\n";
echo $stack->push(20) . "\n";
echo $stack->push(30) . "\n";echo "Top: " . $stack->peek() . "\n";echo "Popped: " . $stack->pop() . "\n";$stack->display();?>
⚡ Time Complexity
| Operation | Complexity |
|---|---|
| Push | O(1) |
| Pop | O(1) |
| Peek | O(1) |
🎯 Advantages
✅ Easy to implement
✅ Fast operations (O(1))
✅ Uses built-in array features
❌ Disadvantages
❌ Fixed size (if defined)
❌ Possible overflow
❌ Memory wastage
🧠 Real-World Use Cases
- Undo/Redo operations
- Expression evaluation
- Backtracking algorithms
- Browser history
🧠 Interview Tips
👉 Common questions:
- Implement stack without using built-in functions
- Two stacks in one array
- Min stack problem
👉 Important:
👉 Always handle:
- Stack Overflow
- Stack Underflow
🏁 Conclusion
Implementing a stack using an array is the most basic and efficient approach.
👉 It helps you understand:
- LIFO principle
- Memory management
- Core stack operations
No comments yet! You be the first to comment.
