Algorithms and Data Structures in PHP: From Basics to Implementation
In modern web development, knowledge of algorithms and data structures is not just an academic skill, but a practical tool for creating fast, scalable, and reliable applications. PHP, despite its reputation as a "language for simple websites," provides all the necessary tools for implementing complex computational tasks. In this article, we will break down key data structures and algorithms, and most importantly, show how to implement them in pure PHP with code examples.
1. Fundamental Data Structures in PHP
In PHP, built-in types (arrays, objects) already cover many needs, but for deep understanding and optimization, it's worth implementing classic structures manually.
1.1. Stack
A stack works on the LIFO (Last In, First Out) principle. It is used for undo actions, bracket parsing, and depth-first graph traversal.
<?phpclass Stack { private array $items = [];
public function push($item): void { array_push($this->items, $item); }
public function pop() { if ($this->isEmpty()) { throw new UnderflowException('Stack is empty'); } return array_pop($this->items); }
public function peek() { return end($this->items); }
public function isEmpty(): bool { return empty($this->items); }
public function size(): int { return count($this->items); }}
// Example: checking bracket balancefunction isBalanced(string $expression): bool { $stack = new Stack(); $pairs = ['(' => ')', '{' => '}', '[' => ']'];
for ($i = 0; $i < strlen($expression); $i++) { $char = $expression[$i]; if (isset($pairs[$char])) { $stack->push($char); } elseif (in_array($char, $pairs)) { if ($stack->isEmpty() || $pairs[$stack->pop()] !== $char) { return false; } } } return $stack->isEmpty();}
echo isBalanced("({[]})") ? "Balanced" : "Not balanced"; // Balanced?>1.2. Queue
A queue works on the FIFO (First In, First Out) principle. It is used in task queue systems, BFS (breadth-first search), and data buffering.
<?phpclass Queue { private array $items = [];
public function enqueue($item): void { $this->items[] = $item; }
public function dequeue() { if ($this->isEmpty()) { throw new UnderflowException('Queue is empty'); } return array_shift($this->items); }
public function peek() { return $this->items[0] ?? null; }
public function isEmpty(): bool { return empty($this->items); }
public function size(): int { return count($this->items); }}
// Example: print queue simulation$printQueue = new Queue();$printQueue->enqueue("document1.pdf");$printQueue->enqueue("photo.jpg");$printQueue->enqueue("report.docx");
while (!$printQueue->isEmpty()) { echo "Printing: " . $printQueue->dequeue() . "";}?>1.3. Binary Search Tree (BST)
A tree provides fast search, insertion, and deletion of elements (O(log n) on average).
<?phpclass TreeNode { public $value; public ?TreeNode $left = null; public ?TreeNode $right = null;
public function __construct($value) { $this->value = $value; }}
class BinarySearchTree { public ?TreeNode $root = null;
public function insert($value): void { $this->root = $this->insertNode($this->root, $value); }
private function insertNode(?TreeNode $node, $value): TreeNode { if ($node === null)