Lesson 1
Stacks and Their Applications in PHP
Introduction

Greetings, Space Explorer! Today, we're diving into Stacks in PHP, a crucial data structure. A stack is like a pile of dishes: you add a dish to the top (Last In) and take it from the top (First Out). This Last-In, First-Out (LIFO) principle exemplifies the stack. In PHP, stacks are implemented using arrays. This lesson will illuminate the stack data structure, its operations, and its applications in PHP. Are you ready to start?

Utilizing Stacks in PHP

In PHP, the behavior of stacks is achieved with arrays. To add an element to the stack, we use the array_push() function, which adds an element to the end of the array. To remove the last element from the stack, simulating the 'top' element removal, we use the array_pop() function. Here's how it looks:

php
1<?php 2 3$stack = []; // A new empty stack 4 5// Push operations 6array_push($stack, "John"); 7array_push($stack, "Mary"); 8array_push($stack, "Steve"); 9 10array_pop($stack); // Pop operation removes 'Steve' 11 12echo implode(" -> ", $stack) . "\n"; // Outputs: John -> Mary 13 14?>

In the example provided, we push John, Mary, and Steve into the stack and then pop Steve from the stack.

Note: An alternative way to implement a stack is to use the SplStack class from the standard library, feel free to ask me questions if you are curious about that!

Advanced Stack Operations

Stack operations go beyond merely Push and Pop. For example, to verify if a stack is empty, we can check if the count() of the array is 0. To peek at the top element of the stack without popping it, we use the end() function.

Here's an example:

php
1<?php 2 3$stack = []; 4array_push($stack, "Steve"); 5array_push($stack, "Sam"); 6 7echo end($stack) . '\n'; // Outputs: 'Sam' 8 9echo empty($stack) ? 'true' : 'false'; // Outputs: false 10echo PHP_EOL; 11array_pop($stack); // Remove 'Sam' 12array_pop($stack); // Remove 'Steve' 13echo empty($stack) ? 'true' : 'false'; // Outputs: true 14echo PHP_EOL; 15 16?>

In this example, Sam is added (pushed), and then the topmost stack element, which is Sam, is peeked at.

Practical Stack Applications: Reversing a String

Practical applications of stacks in PHP are plentiful. Here is one of them — reversing a string.

We will push all characters into a stack and then pop them out to get a reversed string!

php
1<?php 2 3function reverse($input) 4{ 5 $stack = []; 6 foreach (str_split($input) as $char) { 7 array_push($stack, $char); 8 } 9 $reversedString = ''; 10 while (count($stack) > 0) { 11 $reversedString .= array_pop($stack); 12 } 13 return $reversedString; 14} 15 16echo reverse("HELLO") . "\n"; // Outputs: OLLEH 17 18?>
Practical Stack Applications: Checking Balance of Parentheses

A stack can be utilized to verify if parentheses in an expression are well-matched; i.e., every bracket has a corresponding pair. For example, parentheses in the string "()[{}]" are well-matched, while those in the strings "([]()", ")()[]{}", "([)]", and "[{})" are not.

Let's break down the solution into simple steps:

We start by creating an associative array that maps each closing bracket to its corresponding opening bracket and an empty stack. Then, we iterate over each character paren in the string parenString:

  • If paren is an opening bracket, it gets appended to the stack.
  • If paren is a closing bracket and the top element in the stack is the corresponding opening bracket, we remove the top element from the stack.
  • If neither of the above conditions is met, we return false.

Finally, if the stack is empty (all opening brackets had matching closing brackets), we return true. If there are some unmatched opening brackets left, we return false.

php
1<?php 2 3function isParenBalanced($parenString) 4{ 5 $stack = []; 6 $openingParen = [ 7 ')' => '(', 8 ']' => '[', 9 '}' => '{' 10 ]; 11 12 foreach (str_split($parenString) as $paren) { 13 if (in_array($paren, $openingParen)) { 14 array_push($stack, $paren); 15 } elseif (isset($openingParen[$paren])) { 16 if (empty($stack) || array_pop($stack) != $openingParen[$paren]) { 17 return false; 18 } 19 } 20 } 21 22 return empty($stack); 23} 24 25echo isParenBalanced("(())") ? 'true' : 'false'; // Outputs: True 26echo PHP_EOL; 27echo isParenBalanced("({[)}") ? 'true' : 'false'; // Outputs: False 28echo PHP_EOL; 29 30?>
Lesson Summary

Kudos to you! Covering the stack data structure, its operations, and their applications in PHP is a commendable feat. Next up, you'll encounter practice exercises that will solidify your newly acquired knowledge. Dive into them and master Stacks in PHP!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.