A stack is a simple data structure that lets you add and remove items in a
specific order. This order can be LIFO (Last In First Out) or FILO (First In
Last Out). In PHP, the Ds\Stack uses Ds\Vector internally.
Requirements
To use Ds\Stack, you need PHP 7.
Installation
The easiest way to install this data structure is with the PECL extension. Run
this command:
pecl install ds
Syntax
public Ds\Stack::functionName()
Example
Here is an example that shows how to use the `Ds\Stack::pop()` function in
PHP:
<?php // Create a Stack instance $stack = new \Ds\Stack(); // Add items to the stack $stack->push("Welcome"); $stack->push("to"); $stack->push("GfG"); // Print the stack print_r($stack); // Remove the top item and print it print_r($stack->pop()); // Print the stack again print_r($stack); ?>
Output
Ds\Stack Object ( [0] => GfG [1] => to [2] => Welcome ) GfG Ds\Stack Object ( [0] => to [1] => Welcome )
This example shows how to create a stack, add items, and remove the top item
using PHP.
Complete list of data structure DS\Stack:
Ds\Stack Functions | Description |
---|---|
clear() | Remove all elements from the stack. |
copy() | Create a new stack that is a shallow copy of the original stack. Changes to the original stack will not be reflected in the copy, and vice versa. |
isEmpty() | Check whether the stack is empty (contains no elements). |
peek() | Return the value at the top of the stack without removing it. If the stack is empty, it may return an error or null value. |
pop() | Remove and return the element at the top of the stack. If the stack is empty, it may return an error or null value. |
push(value) | Add a new element to the end (top) of the stack. |
toArray() | Convert the stack to a regular PHP array. The elements will be in the reverse order of their insertion (Last In First Out - LIFO). |