Home >Backend Development >PHP Tutorial >PHP Master | Data Structures for PHP Devs: Stacks and Queues
<span><span><?php </span></span><span><span>class ReadingList </span></span><span><span>{ </span></span><span> <span>protected $stack; </span></span><span> <span>protected $limit; </span></span><span> </span><span> <span>public function __construct($limit = 10) { </span></span><span> <span>// initialize the stack </span></span><span> <span>$this->stack = array(); </span></span><span> <span>// stack can only contain this many items </span></span><span> <span>$this->limit = $limit; </span></span><span> <span>} </span></span><span> </span><span> <span>public function push($item) { </span></span><span> <span>// trap for stack overflow </span></span><span> <span>if (count($this->stack) < $this->limit) { </span></span><span> <span>// prepend item to the start of the array </span></span><span> <span>array_unshift($this->stack, $item); </span></span><span> <span>} else { </span></span><span> <span>throw new RunTimeException('Stack is full!'); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>public function pop() { </span></span><span> <span>if ($this->isEmpty()) { </span></span><span> <span>// trap for stack underflow </span></span><span> <span>throw new RunTimeException('Stack is empty!'); </span></span><span> <span>} else { </span></span><span> <span>// pop item from the start of the array </span></span><span> <span>return array_shift($this->stack); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>public function top() { </span></span><span> <span>return current($this->stack); </span></span><span> <span>} </span></span><span> </span><span> <span>public function isEmpty() { </span></span><span> <span>return empty($this->stack); </span></span><span> <span>} </span></span><span><span>}</span></span>In this example, I’ve used array_unshift() and array_shift(), rather than array_push() and array_pop(), so that the first element of the stack is always the top. You could use array_push() and array_pop() to maintain semantic consistency, in which case, the Nth element of the stack becomes the top. It makes no difference either way since the whole purpose of an abstract data type is to abstract the manipulation of the data from its actual implementation. Let’s add some items to the stack:
<span><span><?php </span></span><span><span>$myBooks = new ReadingList(); </span></span><span> </span><span><span>$myBooks->push('A Dream of Spring'); </span></span><span><span>$myBooks->push('The Winds of Winter'); </span></span><span><span>$myBooks->push('A Dance with Dragons'); </span></span><span><span>$myBooks->push('A Feast for Crows'); </span></span><span><span>$myBooks->push('A Storm of Swords'); </span></span><span><span>$myBooks->push('A Clash of Kings'); </span></span><span><span>$myBooks->push('A Game of Thrones');</span></span>To remove some items from the stack:
<span><span><?php </span></span><span><span>echo $myBooks->pop(); // outputs 'A Game of Thrones' </span></span><span><span>echo $myBooks->pop(); // outputs 'A Clash of Kings' </span></span><span><span>echo $myBooks->pop(); // outputs 'A Storm of Swords'</span></span>Let’s see what’s at the top of the stack:
<span><span><?php </span></span><span><span>echo $myBooks->top(); // outputs 'A Feast for Crows'</span></span>What if we remove it?
<span><span><?php </span></span><span><span>echo $myBooks->pop(); // outputs 'A Feast for Crows'</span></span>And if we add a new item?
<span><span><?php </span></span><span><span>$myBooks->push('The Armageddon Rag'); </span></span><span><span>echo $myBooks->pop(); // outputs 'The Armageddon Rag'</span></span>You can see the stack operates on a last in first out basis. Whatever is last added to the stack is the first to be removed. If you continue to pop items until the stack is empty, you’ll get a stack underflow runtime exception.
PHP Fatal error: Uncaught exception 'RuntimeException' with message 'Stack is empty!' in /home/ignatius/Data Structures/code/array_stack.php:33 Stack trace: #0 /home/ignatius/Data Structures/code/example.php(31): ReadingList->pop() #1 /home/ignatius/Data Structures/code/array_stack.php(54): include('/home/ignatius/...') #2 {main} thrown in /home/ignatius/Data Structures/code/array_stack.php on line 33Oh, hello… PHP has kindly provided a stack trace showing the program execution call stack prior and up to the exception!
<span><span><?php </span></span><span><span>class ReadingList extends SplStack </span></span><span><span>{ </span></span><span><span>}</span></span>The SplStack class implements a few more methods than we’ve originally defined. This is because SplStack is implemented as a doubly-linked list, which provides the capacity to implement a traversable stack. A linked list, which is another abstract data type itself, is a linear collection of objects (nodes) used to represent a particular sequence, where each node in the collection maintains a pointer to the next node in collection. In its simplest form, a linked list looks something like this:
<span><span><?php </span></span><span><span>class ReadingList </span></span><span><span>{ </span></span><span> <span>protected $stack; </span></span><span> <span>protected $limit; </span></span><span> </span><span> <span>public function __construct($limit = 10) { </span></span><span> <span>// initialize the stack </span></span><span> <span>$this->stack = array(); </span></span><span> <span>// stack can only contain this many items </span></span><span> <span>$this->limit = $limit; </span></span><span> <span>} </span></span><span> </span><span> <span>public function push($item) { </span></span><span> <span>// trap for stack overflow </span></span><span> <span>if (count($this->stack) < $this->limit) { </span></span><span> <span>// prepend item to the start of the array </span></span><span> <span>array_unshift($this->stack, $item); </span></span><span> <span>} else { </span></span><span> <span>throw new RunTimeException('Stack is full!'); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>public function pop() { </span></span><span> <span>if ($this->isEmpty()) { </span></span><span> <span>// trap for stack underflow </span></span><span> <span>throw new RunTimeException('Stack is empty!'); </span></span><span> <span>} else { </span></span><span> <span>// pop item from the start of the array </span></span><span> <span>return array_shift($this->stack); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>public function top() { </span></span><span> <span>return current($this->stack); </span></span><span> <span>} </span></span><span> </span><span> <span>public function isEmpty() { </span></span><span> <span>return empty($this->stack); </span></span><span> <span>} </span></span><span><span>}</span></span>To traverse the stack in reverse order, we simply set the iterator mode to FIFO (first in, first out):
<span><span><?php </span></span><span><span>$myBooks = new ReadingList(); </span></span><span> </span><span><span>$myBooks->push('A Dream of Spring'); </span></span><span><span>$myBooks->push('The Winds of Winter'); </span></span><span><span>$myBooks->push('A Dance with Dragons'); </span></span><span><span>$myBooks->push('A Feast for Crows'); </span></span><span><span>$myBooks->push('A Storm of Swords'); </span></span><span><span>$myBooks->push('A Clash of Kings'); </span></span><span><span>$myBooks->push('A Game of Thrones');</span></span>
<span><span><?php </span></span><span><span>class ReadingList </span></span><span><span>{ </span></span><span> <span>protected $stack; </span></span><span> <span>protected $limit; </span></span><span> </span><span> <span>public function __construct($limit = 10) { </span></span><span> <span>// initialize the stack </span></span><span> <span>$this->stack = array(); </span></span><span> <span>// stack can only contain this many items </span></span><span> <span>$this->limit = $limit; </span></span><span> <span>} </span></span><span> </span><span> <span>public function push($item) { </span></span><span> <span>// trap for stack overflow </span></span><span> <span>if (count($this->stack) < $this->limit) { </span></span><span> <span>// prepend item to the start of the array </span></span><span> <span>array_unshift($this->stack, $item); </span></span><span> <span>} else { </span></span><span> <span>throw new RunTimeException('Stack is full!'); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>public function pop() { </span></span><span> <span>if ($this->isEmpty()) { </span></span><span> <span>// trap for stack underflow </span></span><span> <span>throw new RunTimeException('Stack is empty!'); </span></span><span> <span>} else { </span></span><span> <span>// pop item from the start of the array </span></span><span> <span>return array_shift($this->stack); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> </span><span> <span>public function top() { </span></span><span> <span>return current($this->stack); </span></span><span> <span>} </span></span><span> </span><span> <span>public function isEmpty() { </span></span><span> <span>return empty($this->stack); </span></span><span> <span>} </span></span><span><span>}</span></span>SplDoublyLinkedList also implements the ArrayAccess interface so you can also add items to both SplQueue and SplStack as array elements:
<span><span><?php </span></span><span><span>$myBooks = new ReadingList(); </span></span><span> </span><span><span>$myBooks->push('A Dream of Spring'); </span></span><span><span>$myBooks->push('The Winds of Winter'); </span></span><span><span>$myBooks->push('A Dance with Dragons'); </span></span><span><span>$myBooks->push('A Feast for Crows'); </span></span><span><span>$myBooks->push('A Storm of Swords'); </span></span><span><span>$myBooks->push('A Clash of Kings'); </span></span><span><span>$myBooks->push('A Game of Thrones');</span></span>To remove items from the front of the queue:
<span><span><?php </span></span><span><span>echo $myBooks->pop(); // outputs 'A Game of Thrones' </span></span><span><span>echo $myBooks->pop(); // outputs 'A Clash of Kings' </span></span><span><span>echo $myBooks->pop(); // outputs 'A Storm of Swords'</span></span>enqueue() is an alias for push(), but note that dequeue() is not an alias for pop(); pop() has a different meaning and function in the context of a queue. If we had used pop() here, it would remove the item from the end (tail) of the queue which violates the FIFO rule. Similarly, to see what’s at the front (head) of the queue, we have to use bottom() instead of top():
<span><span><?php </span></span><span><span>echo $myBooks->top(); // outputs 'A Feast for Crows'</span></span>
PHP supports several types of data structures, including arrays, objects, and resources. Arrays are the most common and versatile data structures in PHP. They can hold any type of data, including other arrays, and can be indexed or associative. Objects in PHP are instances of classes, which can have properties and methods. Resources are special variables that hold references to external resources, such as database connections.
A stack is a type of data structure that follows the LIFO (Last In, First Out) principle. In PHP, you can use the SplStack class to implement a stack. You can push elements onto the stack using the push() method, and pop elements off the stack using the pop() method.
Arrays and objects in PHP are both types of data structures, but they have some key differences. Arrays are simple lists of values, while objects are instances of classes and can have properties and methods. Arrays can be indexed or associative, while objects always use string keys. Arrays are more versatile and easier to use, while objects provide more structure and encapsulation.
Using the right data structure can significantly improve the performance of your PHP code. For example, if you need to store a large number of elements and frequently search for specific elements, using a hash table or a set can be much faster than using an array. Similarly, if you need to frequently add and remove elements at both ends, using a deque can be more efficient than using an array.
The SplDoublyLinkedList class in PHP is a data structure that implements a doubly linked list. It allows you to add, remove, and access elements at both ends of the list in constant time. It also provides methods for iterating over the elements in the list, and for sorting the elements.
A queue is a type of data structure that follows the FIFO (First In, First Out) principle. In PHP, you can use the SplQueue class to implement a queue. You can enqueue elements onto the queue using the enqueue() method, and dequeue elements off the queue using the dequeue() method.
A stack and a queue are both types of data structures, but they have a key difference in how elements are added and removed. A stack follows the LIFO (Last In, First Out) principle, meaning that the last element added is the first one to be removed. A queue, on the other hand, follows the FIFO (First In, First Out) principle, meaning that the first element added is the first one to be removed.
The SplHeap class in PHP is a data structure that implements a heap. A heap is a type of binary tree where each parent node is less than or equal to its child nodes. You can use the SplHeap class to create a min-heap or a max-heap, and to add, remove, and access elements in the heap.
Using data structures in PHP can provide several benefits. They can help you organize your data in a more efficient and logical way, which can make your code easier to understand and maintain. They can also improve the performance of your code, especially when dealing with large amounts of data or complex operations.
A binary tree is a type of data structure where each node has at most two children, referred to as the left child and the right child. In PHP, you can implement a binary tree using a class that has properties for the value of the node and the left and right children. You can then use methods to add, remove, and search for nodes in the tree.
The above is the detailed content of PHP Master | Data Structures for PHP Devs: Stacks and Queues. For more information, please follow other related articles on the PHP Chinese website!