Fundamentals 3 min read

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.

21CTO
21CTO
21CTO
Master PHP Data Structures: Stack, Queue, and Min-Heap with SPL

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:

Min-heap illustration
Min-heap illustration

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);
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPStackData StructuresHeapQueueSPL
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.