Master PHP Data Structures: Stack, Queue, and Min-Heap with SPL
This article explains the concept of heaps, especially min‑heaps, and demonstrates how PHP's SPL provides ready‑made implementations for stacks, queues, min‑heaps, and fixed‑size arrays with clear code examples.
Heap is a data structure designed to implement priority queues, typically built using a binary heap. A heap where the root is the largest is called a max‑heap, while a heap where the root is the smallest is a min‑heap, which is also used for heap sort.
The following diagram illustrates a min‑heap where each node’s priority is not less than that of its children:
PHP’s Standard PHP Library (SPL) provides built‑in implementations of common data structures. While arrays can be used to simulate stacks or queues, they are not specialized and can lead to errors. SPL classes such as SplStack, SplQueue, SplMinHeap, and SplFixedArray offer dedicated, efficient implementations.
Stack implementation
$stack = new SplStack();
// push
$stack->push('a');
$stack->push('b');
// pop
echo $stack->pop();
echo $stack->pop();Queue implementation
$queue = new SplQueue();
// enqueue
$queue->enqueue('a');
$queue->enqueue('b');
$queue->enqueue('c');
// dequeue
echo $queue->dequeue();
echo $queue->dequeue();
echo $queue->dequeue();Min‑heap implementation
$heap = new SplMinHeap();
// insert
$heap->insert('a');
$heap->insert('b');
// extract
echo $heap->extract();
echo $heap->extract();Fixed‑length array
$array = new SplFixedArray(5);
$array[1] = 5;
var_dump($array);Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
