Data Structures for PHP Devs: Stacks and Queues with Example
Two basic abstract data types — stack and queue.
Published in
1 min readFeb 17, 2019
What is Stacks?
A stack is a sequential collection with a particular property, in that, the last object placed on the stack, will be the first object removed. This property is commonly referred to as last in first out, or LIFO.
- init — create the stack.
- push — add an item to the top of the stack.
- pop — remove the last item added to the top of the stack.
- top — look at the item on the top of the stack without removing it.
- isEmpty — return whether the stack contains no more items.
Example:
array_shift() — Removes the first element in the array.
array_unshift() — Added new variables as the first element in the array.
Let’s add some items to the stack:
$stack = new Stack(10, array(1, 2, 3, 4, 5));//OR$stack = new Stack();
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->push(4);
To remove some items from the stack:
echo $stack->pop(); // outputs '4'
Let’s see what’s at the top of the stack:
echo $stack->top(); // outputs '3'
Thanks for reading out.
Reference From: https://www.sitepoint.com/php-data-structures-1/