Lab 05: SPL Data Structures

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

The Standard PHP Library (SPL) provides specialized data structures with O(1) operations for specific access patterns. Knowing when to use them over plain arrays can significantly improve performance and code clarity.


Step 1: SplStack — LIFO Stack

<?php
$stack = new SplStack();

$stack->push('a');
$stack->push('b');
$stack->push('c');

echo "Top:  " . $stack->top() . "\n";    // c (peek)
echo "Pop:  " . $stack->pop() . "\n";    // c
echo "Pop:  " . $stack->pop() . "\n";    // b
echo "Size: " . $stack->count() . "\n";  // 1

// Iterate (top to bottom)
$stack->push('x');
$stack->push('y');
foreach ($stack as $item) {
    echo $item . " ";
}
echo "\n";

📸 Verified Output:

💡 SplStack extends SplDoublyLinkedList with LIFO iteration mode. Use it for undo history, call stacks, and expression parsers.


Step 2: SplQueue — FIFO Queue

📸 Verified Output:


Step 3: SplPriorityQueue

📸 Verified Output:

💡 SplPriorityQueue is a max-heap. Higher numbers have higher priority. Use EXTR_BOTH to retrieve both data and priority.


Step 4: SplMinHeap & SplMaxHeap

📸 Verified Output:


Step 5: SplFixedArray — Memory-Efficient Arrays

📸 Verified Output:

💡 SplFixedArray uses ~30% less memory than a PHP array for large integer-indexed data, since it doesn't need hash table overhead.


Step 6: SplObjectStorage — Object Registry

📸 Verified Output:


Step 7: SplDoublyLinkedList — Bidirectional Traversal

📸 Verified Output:


Step 8: Capstone — Performance Benchmark Suite

📸 Verified Output:


Summary

Structure
Best For
Key Operations

SplStack

LIFO, undo, recursion

push(), pop(), top()

SplQueue

FIFO, task queue, BFS

enqueue(), dequeue(), bottom()

SplPriorityQueue

Priority scheduling

insert($data, $priority), extract()

SplMinHeap

Find minimum fast

insert(), extract() O(log n)

SplMaxHeap

Find maximum fast

insert(), extract() O(log n)

SplFixedArray

Large integer arrays

30% less memory than array

SplObjectStorage

Object → data map

attach(), detach(), contains()

SplDoublyLinkedList

Bidirectional traversal

push(), unshift(), shift(), pop()

Last updated