PHP Master | Data Structures for PHP Devs: Stacks and Queues
Key Takeaways
- Abstract Data Types (ADTs) are models defined by a set of operations that can be performed on them. Stacks and queues are basic ADTs with origins in everyday usage. In computer science, a stack is a sequential collection where the last object placed is the first removed (LIFO), while a queue operates on a first-in, first-out basis (FIFO).
- A stack can be implemented using arrays, as they already provide push and pop operations. The basic operations defining a stack include init (create the stack), push (add an item to the top), pop (remove the last item added), top (look at the item on top without removing it), and isEmpty (return whether the stack contains no more items).
- The SPL extension in PHP provides a set of standard data structures, including the SplStack class. The SplStack class, implemented as a doubly-linked list, provides the capacity to implement a traversable stack. The ReadingList class, implemented as an SplStack, can traverse the stack forward (top-down) and backward (bottom-up).
- A queue, another abstract data type, operates on a first-in, first-out basis (FIFO). The basic operations defining a queue include init (create the queue), enqueue (add an item to the end), dequeue (remove an item from the front), and isEmpty (return whether the queue contains no more items). The SplQueue class in PHP, also implemented using a doubly-linked list, allows for the implementation of a queue.
Stacks
In common usage, a stack is a pile of objects which are typically arranged in layers – for example, a stack of books on your desk, or a stack of trays in the school cafeteria. In computer science parlance, 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. Candy, chip, and cigarette vending machines operate on the same principle; the last item loaded in the rack is dispensed first. In abstract terms, a stack is a linear list of items in which all additions to (a “push”) and deletions from (a “pop”) the list are restricted to one end – defined as the “top” (of the stack). The basic operations which define a stack are:- 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.
<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>
<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>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>
<span><span><?php </span></span><span><span>echo $myBooks->top(); // outputs 'A Feast for Crows'</span></span>
<span><span><?php </span></span><span><span>echo $myBooks->pop(); // outputs 'A Feast for Crows'</span></span>
<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>
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 33
The SPLStack
The SPL extension provides a set of standard data structures, including the SplStack class (PHP5 >= 5.3.0). We can implement the same object, although much more tersely, using an SplStack as follows:<span><span><?php </span></span><span><span>class ReadingList extends SplStack </span></span><span><span>{ </span></span><span><span>}</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>
<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>
Queues
If you’ve ever been in a line at the supermarket checkout, then you’ll know that the first person in line gets served first. In computer terminology, a queue is another abstract data type, which operates on a first in first out basis, or FIFO. Inventory is also managed on a FIFO basis, particularly if such items are of a perishable nature. The basic operations which define a queue are:- init – create the queue.
- enqueue – add an item to the “end” (tail) of the queue.
- dequeue – remove an item from the “front” (head) of the queue.
- isEmpty – return whether the queue contains no more items.
<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>
<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>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>
<span><span><?php </span></span><span><span>echo $myBooks->top(); // outputs 'A Feast for Crows'</span></span>
Summary
In this article, you’ve seen how the stack and queue abstract data types are used in programming. These data structures are abstract, in that they are defined by the operations that can be performed on itself, thereby creating a wall between its implementation and the underlying data. These structures are also constrained by the effect of such operations: You can only add or remove items from the top of the stack, and you can only remove items from the front of the queue, or add items to the rear of the queue. Image by Alexandre Dulaunoy via FlickrFrequently Asked Questions (FAQs) about PHP Data Structures
What are the different types of data structures in PHP?
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.
How can I implement a stack in PHP?
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.
What is the difference between arrays and objects in PHP?
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.
How can I use data structures to improve the performance of my PHP code?
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.
What is the SplDoublyLinkedList class in PHP?
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.
How can I implement a queue in PHP?
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.
What is the difference between a stack and a queue in PHP?
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.
How can I use the SplHeap class in PHP?
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.
What are the benefits of using data structures in PHP?
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.
How can I implement a binary tree in PHP?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
