SplFixedArray, SplStack, SplQueue — typed array structures
Concept
PHP's Standard PHP Library (SPL) provides typed, specialized data structures that are more memory-efficient or semantically precise than generic arrays. They're useful in performance-critical code or when you want to enforce a specific data structure contract at the API level.
SplFixedArray is a fixed-size array of integers. Unlike PHP's dynamic array, it allocates a contiguous block of memory and only supports integer keys. Memory usage is roughly 4× less than a standard PHP array. Drawback: size is fixed at creation (you can resize but it's expensive). Use it when the size is known upfront and memory is a constraint.
SplStack implements a Last-In-First-Out (LIFO) stack. Operations: push($val), pop(), top(). Internally doubly-linked. Use when your algorithm explicitly needs stack semantics (depth-first traversal, undo stacks, expression evaluation).
SplQueue implements a First-In-First-Out (FIFO) queue. Operations: enqueue($val), dequeue(). Use for breadth-first traversal, job queues, or producer-consumer patterns within a single process.
SplMinHeap / SplMaxHeap: Priority queues. insert($val), extract() (removes and returns minimum/maximum). Use for Dijkstra's algorithm, event scheduling, or any ordered-extraction pattern.
SplDoublyLinkedList: The base class for Stack and Queue. Supports O(1) insertion/removal at both ends. More flexible but less semantically expressive than Stack/Queue.
Code Example
<?php
declare(strict_types=1);
// SplFixedArray — memory-efficient integer array
$size = 1_000_000;
$before = memory_get_usage();
$fixed = new SplFixedArray($size);
for ($i = 0; $i < $size; $i++) $fixed[$i] = $i;
echo "SplFixedArray: " . (memory_get_usage() - $before) . " bytes\n"; // ~16MB
$before = memory_get_usage();
$phpArr = range(0, $size - 1);
echo "PHP array: " . (memory_get_usage() - $before) . " bytes\n"; // ~67MB
// Convert between SplFixedArray and array
$arr = [1, 2, 3, 4, 5];
$fixed = SplFixedArray::fromArray($arr);
$back = $fixed->toArray();
// SplStack — LIFO
$stack = new SplStack();
$stack->push('first');
$stack->push('second');
$stack->push('third');
echo $stack->pop(); // "third" — LIFO
echo $stack->top(); // "second" — peek without removing
// DFS traversal using stack
function dfs(array $tree, int $root): array
{
$visited = [];
$stack = new SplStack();
$stack->push($root);
while (!$stack->isEmpty()) {
$node = $stack->pop();
$visited[] = $node;
foreach ($tree[$node] ?? [] as $child) {
$stack->push($child);
}
}
return $visited;
}
// SplQueue — FIFO
$queue = new SplQueue();
$queue->enqueue('job-1');
$queue->enqueue('job-2');
$queue->enqueue('job-3');
echo $queue->dequeue(); // "job-1" — FIFO
// SplMinHeap — always extract smallest
$heap = new SplMinHeap();
$heap->insert(5);
$heap->insert(1);
$heap->insert(3);
while (!$heap->isEmpty()) {
echo $heap->extract() . " "; // "1 3 5" — sorted order
}