Shamim Shams
Shamim Shams
Published on

Part-3: Data Structures in PHP - Stack

Authors

A stack is a fundamental data structure in computer science and is often used to manage data in a Last-In, First-Out (LIFO) manner. PHP, a popular scripting language, provides native support for implementing stacks through arrays. In this article, we will explore how to create and manipulate stacks in PHP, along with a practical example.

Creating a Stack in PHP

In PHP, you can implement a stack using an array. You can use array functions to mimic the behavior of a stack, including pushing (adding) elements onto the stack, popping (removing) elements from the stack, checking if the stack is empty, and accessing the top element.

Let's create a basic stack and perform various operations on it.

// Initialize an empty stack
$stack = array();

// Push elements onto the stack
array_push($stack, 10);
array_push($stack, 20);
array_push($stack, 30);

// Print the stack
print_r($stack);

In this example, we start with an empty array called `$stack` and use the `array_push()` function to add elements (10, 20, and 30) to the stack. The `print_r()` function is used to display the contents of the stack, which will produce the following output:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

 

Popping Elements from the Stack

To pop elements from the stack (remove and return the top element), you can use the `array_pop()` function:

// Pop an element from the stack
$topElement = array_pop($stack);

// Print the updated stack and the popped element
print_r($stack);

echo "Popped element: $topElement";

After popping an element from the stack, the output will look like this:

Array
(
    [0] => 10
    [1] => 20
)

Popped element: 30

 

Checking if the Stack is Empty

You can check if the stack is empty using the `empty()` function:

if (empty($stack)) {
    echo "Stack is empty.";
} else {
    echo "Stack is not empty.";
}

 

Accessing the Top Element of the Stack

To access the top element of the stack (without removing it), you can use the `end()` function:

$topElement = end($stack);
echo "Top element: $topElement";

 

In this article, we've explored how to create and manipulate stacks in PHP using arrays. Stacks are useful for various applications, including parsing expressions, tracking function calls, and managing undo/redo functionality. Understanding how to implement and work with stacks is an essential skill for any PHP developer, and PHP's built-in array functions make it relatively straightforward to do so.