PHP Master | Data Structures for PHP Devs: Stacks and Queues
Feb 23, 2025 am 11:35 AMKey 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>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!
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>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>
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>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>
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

Undress AI Tool
Undress images for free

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

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

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











Upgrading the PHP version is actually not difficult, but the key lies in the operation steps and precautions. The following are the specific methods: 1. Confirm the current PHP version and running environment, use the command line or phpinfo.php file to view; 2. Select the suitable new version and install it. It is recommended to install it with 8.2 or 8.1. Linux users use package manager, and macOS users use Homebrew; 3. Migrate configuration files and extensions, update php.ini and install necessary extensions; 4. Test whether the website is running normally, check the error log to ensure that there is no compatibility problem. Follow these steps and you can successfully complete the upgrade in most situations.

To set up a PHP development environment, you need to select the appropriate tools and install the configuration correctly. ①The most basic PHP local environment requires three components: the web server (Apache or Nginx), the PHP itself and the database (such as MySQL/MariaDB); ② It is recommended that beginners use integration packages such as XAMPP or MAMP, which simplify the installation process. XAMPP is suitable for Windows and macOS. After installation, the project files are placed in the htdocs directory and accessed through localhost; ③MAMP is suitable for Mac users and supports convenient switching of PHP versions, but the free version has limited functions; ④ Advanced users can manually install them by Homebrew, in macOS/Linux systems

TosetupaPHPdevelopmentenvironmentonLinux,installPHPandrequiredextensions,setupawebserverlikeApacheorNginx,testwithaPHPfile,andoptionallyinstallMySQLandComposer.1.InstallPHPandextensionsviapackagemanager(e.g.,sudoaptinstallphpphp-mysqlphp-curlphp-mbst

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

TopreventCSRFattacksinPHP,implementanti-CSRFtokens.1)Generateandstoresecuretokensusingrandom_bytes()orbin2hex(random_bytes(32)),savethemin$_SESSION,andincludetheminformsashiddeninputs.2)ValidatetokensonsubmissionbystrictlycomparingthePOSTtokenwiththe

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.
