data types and standard library
SPL Data Structures
The Standard PHP Library includes data structures for queues, stacks, heaps, fixed arrays, object storage, and iterators.
Most everyday PHP code uses arrays, and that is fine. SPL data structures are useful when the operation matters enough that the type should say it clearly: first-in-first-out queues, last-in-first-out stacks, priority processing, memory-conscious fixed lists, or attaching data to object identities.
Use SplQueue for first-in, first-out work
A queue processes the oldest item first.
<?php
declare(strict_types=1);
$queue = new SplQueue();
$queue->enqueue('send welcome email');
$queue->enqueue('generate invoice');
echo $queue->dequeue() . PHP_EOL;
echo $queue->dequeue() . PHP_EOL;
// Prints:
// send welcome email
// generate invoice
This is useful for local work lists, import batches, crawlers, and breadth-first traversal. For production background jobs, you would normally use a real queue system, but SplQueue is still useful inside a process.
Use SplStack for last-in, first-out work
A stack processes the newest item first.
<?php
declare(strict_types=1);
$stack = new SplStack();
$stack->push('open file');
$stack->push('read header');
$stack->push('parse rows');
echo $stack->pop() . PHP_EOL;
echo $stack->pop() . PHP_EOL;
// Prints:
// parse rows
// read header
Stacks are useful for undo operations, depth-first traversal, parsers, and nested work.
Use SplPriorityQueue for most-important-first work
Priority queues return the item with the highest priority first.
<?php
declare(strict_types=1);
$queue = new SplPriorityQueue();
$queue->insert('normal notification', 10);
$queue->insert('payment failed alert', 100);
$queue->insert('weekly digest', 1);
echo $queue->extract() . PHP_EOL;
echo $queue->extract() . PHP_EOL;
// Prints:
// payment failed alert
// normal notification
Use clear priority values. If equal priorities matter, test the behaviour you depend on or add your own tie-breaking data.
Use SplFixedArray when size is known
SplFixedArray is less flexible than a normal array, but can be useful when a fixed numeric list is intentional.
<?php
declare(strict_types=1);
$scores = new SplFixedArray(3);
$scores[0] = 80;
$scores[1] = 92;
$scores[2] = 75;
echo $scores->count() . ' scores' . PHP_EOL;
// Prints:
// 3 scores
For most application lists, normal arrays are easier. Use fixed arrays only when the fixed size communicates something useful.
Use SplObjectStorage for object identity
Arrays use string or integer keys. SplObjectStorage lets you attach data to object instances.
<?php
declare(strict_types=1);
$user = new stdClass();
$user->id = 101;
$storage = new SplObjectStorage();
$storage[$user] = 'already processed';
echo $storage[$user] . PHP_EOL;
// Prints:
// already processed
This is useful in graph traversal, object caching, and tracking visited objects.
SPL iterators compose filesystem and collection work
SPL also includes iterators such as DirectoryIterator, RecursiveDirectoryIterator, and LimitIterator.
<?php
declare(strict_types=1);
$items = new ArrayIterator(['alpha', 'beta', 'gamma']);
$limited = new LimitIterator($items, 1, 2);
foreach ($limited as $item) {
echo $item . PHP_EOL;
}
// Prints:
// beta
// gamma
Iterators are common in libraries because they allow lazy traversal and composition.
When an array is better
Do not use SPL to look clever. If you need a simple list of records, an associative map, or JSON-friendly data, arrays are usually the right choice.
<?php
declare(strict_types=1);
$statusLabels = [
'paid' => 'Paid',
'draft' => 'Draft',
];
echo $statusLabels['paid'] . PHP_EOL;
// Prints:
// Paid
Choose the structure that makes the next developer's job easier.
What to remember
Use SPL data structures when their behaviour is the point: FIFO queues, LIFO stacks, priority queues, fixed-size numeric lists, object identity storage, or iterator composition. Use arrays for ordinary application data.
Practice
Task: Process queued jobs
Write a small job processor using SplQueue.
Requirements
- Use
declare(strict_types=1);. - Create an
SplQueue. - Enqueue at least three job names.
- Process jobs in first-in, first-out order.
- Collect processed job names into an array.
- Print the processed order.
- Show that the queue is empty at the end.
- Include the expected output as comments in the same PHP code block.
The task should make the queue behaviour obvious.
Show solution
<?php
declare(strict_types=1);
$queue = new SplQueue();
$queue->enqueue('send welcome email');
$queue->enqueue('generate invoice');
$queue->enqueue('sync customer record');
$processed = [];
while (!$queue->isEmpty()) {
$processed[] = $queue->dequeue();
}
echo implode(' -> ', $processed) . PHP_EOL;
echo $queue->isEmpty() ? 'queue empty' : 'queue still has work';
echo PHP_EOL;
// Prints:
// send welcome email -> generate invoice -> sync customer record
// queue empty
The solution uses SplQueue because FIFO order is the main behaviour being demonstrated. A normal array could store the names, but the queue type makes enqueueing and dequeueing the intent of the example.