PHP Standard Library Strategies Quiz

PHP
0 Passed
0% acceptance

A 35-question quiz exploring PHP SPL iterators, data structures, autoloading hooks, and stream helpers with 11 concise code walk-throughs for everyday review scenarios.

35 Questions
~70 minutes
1

Question 1

Why do reviewers encourage teams to lean on SPL iterators instead of rolling ad-hoc iterator classes for every collection?

A
SPL iterators provide consistent Traversable behavior, letting foreach, generators, and higher-order utilities interoperate without extra glue code.
B
SPL iterators automatically persist data to disk.
C
Custom iterators are prohibited by the PHP runtime.
D
SPL iterators encrypt array values.
2

Question 2

What does this SplDoublyLinkedList snippet echo?

php
<?php
$list = new SplDoublyLinkedList();
$list->push('header');
$list->push('body');
echo $list->pop();
?>
A
body
B
header
C
0
D
Notice
3

Question 3

Why would SplFixedArray be chosen for a CPU-friendly cache of 10k metrics instead of a plain PHP array?

A
SplFixedArray stores values in a contiguous internal structure with predictable size, reducing memory overhead compared to a dynamic zval hash.
B
SplFixedArray automatically sorts entries by value.
C
SplFixedArray persists contents between requests.
D
Plain arrays cannot hold integers.
4

Question 4

What filenames does this DirectoryIterator loop print?

php
<?php
$dir = new DirectoryIterator(__DIR__ . '/templates');
foreach ($dir as $file) {
  if ($file->isFile()) {
    echo $file->getFilename() . PHP_EOL;
  }
}
?>
A
Only regular files inside templates
B
Only directories inside templates
C
Nothing because DirectoryIterator is abstract
D
All files recursively
5

Question 5

Why would a job scheduler reach for SplPriorityQueue when orchestrating retries?

A
SplPriorityQueue delivers items ordered by priority without full re-sorting on every insert, which suits retry windows and escalation policies.
B
It automatically persists queue contents to Redis.
C
It guarantees FIFO order regardless of priority.
D
It only runs inside CLI scripts.
6

Question 6

What does this SplObjectStorage snippet echo?

php
<?php
$storage = new SplObjectStorage();
$a = new stdClass();
$b = new stdClass();
$storage[$a] = 'alpha';
$storage[$b] = 'beta';
$storage->detach($a);
echo $storage[$b];
?>
A
beta
B
alpha
C
0
D
Notice
7

Question 7

Why is RecursiveIteratorIterator commonly used with RecursiveDirectoryIterator in deployment tooling?

A
RecursiveIteratorIterator flattens nested iterators into a single forward-only traversal, so build scripts can treat deep trees like linear lists.
B
It compresses directories into zip archives automatically.
C
It sorts entries alphabetically by default.
D
It can only iterate over JSON files.
8

Question 8

Why would SplQueue be favored for a producer-consumer worker while SplStack is saved for undo histories?

A
SplQueue is FIFO by design, matching producer-consumer semantics, whereas SplStack is LIFO, matching undo or breadcrumb flows.
B
SplQueue encrypts payloads but SplStack does not.
C
SplStack cannot be iterated.
D
SplQueue only exists in PHP 5.
9

Question 9

What syllables does this LimitIterator example echo?

php
<?php
$inner = new ArrayIterator(['alfa', 'bravo', 'charlie']);
$limit = new LimitIterator($inner, 1, 2);
foreach ($limit as $word) {
  echo substr($word, 0, 1);
}
?>
A
bc
B
ab
C
abc
D
Notice
10

Question 10

Why do file-processing daemons prefer SplFileObject over fopen/fgets pairs when tailing logs?

A
SplFileObject wraps file pointer operations with iterator semantics, letting daemons foreach over lines with fewer manual checks.
B
SplFileObject automatically emails logs to admins.
C
SplFileObject never buffers data.
D
fgets cannot read binary files.
11

Question 11

Why are SplMaxHeap or SplMinHeap better suited for streaming leaderboards than sorting arrays on every update?

A
Heaps maintain the extreme element in O(log n) per insert, so you do not pay O(n log n) each time new scores arrive.
B
Heaps automatically sync with SQL databases.
C
Heaps cannot be iterated.
D
Sorting arrays mutates values unpredictably.
12

Question 12

What does this RegexIterator snippet output?

php
<?php
$it = new ArrayIterator(['error.log', 'readme.md', 'deploy.log']);
$regex = new RegexIterator($it, '/\.log$/');
foreach ($regex as $file) {
  echo $file . '|';
}
?>
A
error.log|deploy.log|
B
readme.md|
C
error.log|readme.md|deploy.log|
D
Notice
13

Question 13

Why do plugin systems occasionally implement SplObserver and SplSubject instead of bespoke event arrays?

A
The observer interfaces standardize attach, detach, and notify semantics, making it easier to swap implementations or integrate multiple plugins frameworks.
B
SplObserver guarantees asynchronous execution.
C
SplSubject encrypts payloads.
D
Observers only support GET requests.
14

Question 14

Why must SplStack be rewound before reusing it in multiple foreach loops?

A
SplStack maintains an internal iterator pointer that stays at the end after one pass, so calling rewind or clone is needed before iterating again.
B
SplStack deletes elements after iteration automatically.
C
SplStack cannot be iterated more than once by design.
D
SplStack requires serialization between loops.
15

Question 15

What does this SplPriorityQueue snippet echo?

php
<?php
$q = new SplPriorityQueue();
$q->insert('critical', 10);
$q->insert('minor', 1);
$q->setExtractFlags(SplPriorityQueue::EXTR_DATA);
echo $q->extract();
?>
A
critical
B
minor
C
10
D
Notice
16

Question 16

Why does SplFixedArray::setSize help long-running daemons avoid memory creep?

A
Adjusting the size releases or allocates slots in one call, avoiding incremental array growth that leaves behind unused zvals.
B
setSize encrypts array contents.
C
setSize automatically persists the structure to disk.
D
Daemons cannot use unset().
17

Question 17

Why is SplObjectStorage handy for tracking entities in memoization layers?

A
It keys entries by object identity, allowing metadata or cache flags to stick to specific instances without spl_object_hash hacks.
B
It automatically clones objects before storing.
C
It serializes objects to JSON by default.
D
It can only hold PDO instances.
18

Question 18

What does this SplQueue snippet echo?

php
<?php
$q = new SplQueue();
$q->enqueue('task1');
$q->enqueue('task2');
$q->dequeue();
echo $q->bottom();
?>
A
task2
B
task1
C
0
D
Notice
19

Question 19

Why do array-like DTOs often extend ArrayObject rather than using raw arrays?

A
ArrayObject offers property-style access, iterator support, and the ability to swap out the underlying storage, making DTOs easier to enhance later.
B
ArrayObject automatically encrypts properties.
C
Raw arrays cannot be json_encode-d.
D
ArrayObject forces immutability.
20

Question 20

Why might CallbackFilterIterator be used in analytics pipelines instead of array_filter subsets?

A
CallbackFilterIterator filters lazily as data streams by, avoiding loading entire datasets into memory the way array_filter would.
B
CallbackFilterIterator automatically memoizes results.
C
array_filter cannot call closures.
D
CallbackFilterIterator only works on strings.
21

Question 21

Why is SplMinHeap a natural fit for top-N dashboards that need the smallest value quickly?

A
SplMinHeap always keeps the minimum at the top, so popping the next value is cheap even as the dataset grows.
B
It sorts in descending order automatically.
C
It persists snapshots to CSV.
D
It only accepts integers.
22

Question 22

What does this SplFileObject snippet echo when reading a CSV line?

php
<?php
$file = new SplFileObject(__DIR__ . '/data/users.csv');
$file->setFlags(SplFileObject::READ_CSV);
$file->seek(1);
$record = $file->current();
echo $record[0];
?>
A
The first column from the second line
B
The entire file contents
C
0
D
Notice
23

Question 23

Why should custom SplSubject implementations always detach observers when shutting down?

A
Detaching ensures long-running processes do not retain references to subscribers that should be garbage collected, preventing memory leaks.
B
Detaching automatically writes to syslog.
C
Observers cannot be reattached later.
D
SplSubject throws if detach is missing.
24

Question 24

Why might SplDoublyLinkedList be configured in FIFO mode when modeling queues that sometimes need random access?

A
You can shift deque-style while still allowing arbitrary seek or iteration over the same list, something SplQueue does not expose directly.
B
FIFO mode encrypts elements.
C
FIFO mode automatically persists to SQLite.
D
SplQueue cannot dequeue.
25

Question 25

Why do autoloading standards lean on spl_autoload_register rather than __autoload?

A
spl_autoload_register supports multiple loaders and explicit ordering, so frameworks can compose PSR-4, legacy, and fallback loaders safely.
B
__autoload is faster than spl_autoload_register.
C
__autoload is only available in CLI mode.
D
spl_autoload_register requires Zend Engine 4.
26

Question 26

What class name does this spl_autoload_register example load?

php
<?php
spl_autoload_register(function ($class) {
  require __DIR__ . '/src/' . $class . '.php';
});
new Services\Mailer();
?>
A
Services\Mailer from src/Services/Mailer.php
B
Mailer from src/Mailer.php regardless of namespace
C
Nothing because spl_autoload_register throws immediately
D
The autoloader looks in vendor/ only
27

Question 27

Why is RecursiveDirectoryIterator often paired with filesystems that include symlink-heavy vendor trees?

A
It exposes flags such as FOLLOW_SYMLINKS and SKIP_DOTS, letting build scripts decide whether to traverse linked directories safely.
B
It replaces rsync entirely.
C
It encrypts directory names.
D
It only works on Linux.
28

Question 28

Why might extension authors implement SplObserver when exposing plugin hooks?

A
The SPL observer interfaces give third parties a familiar contract, reducing onboarding time and encouraging consistent method names.
B
Observers automatically serialize to YAML.
C
Observers can only run once per request.
D
SplObserver requires Symfony components.
29

Question 29

What does this ArrayObject snippet echo after appending?

php
<?php
$list = new ArrayObject(['alpha']);
$list->append('beta');
$it = $list->getIterator();
foreach ($it as $value) {
  $last = $value;
}
echo $last;
?>
A
beta
B
alpha
C
ArrayObject
D
Notice
30

Question 30

Why do data-merging jobs use MultipleIterator when combining price feeds from separate iterators?

A
MultipleIterator synchronizes traversal so the nth elements of each attached iterator line up, making pairwise aggregation straightforward.
B
It sorts all feeds automatically.
C
It casts everything to strings.
D
It disables exceptions in inner iterators.
31

Question 31

Why does SplPriorityQueue extract elements in heap order even if you iterate with foreach?

A
Iterating SplPriorityQueue calls extract internally, meaning the queue is consumed in priority order and emptied unless you clone it first.
B
foreach forces FIFO order on any iterator.
C
SplPriorityQueue caches results and replays them.
D
Priority queues cannot be cloned.
32

Question 32

Why might SplFixedArray be converted to a regular array before passing data to json_encode?

A
json_encode expects arrays or objects; casting SplFixedArray to a plain array avoids JSON encoding the internal object metadata.
B
json_encode cannot handle arrays at all.
C
Casting encrypts values.
D
SplFixedArray cannot be iterated.
33

Question 33

What does this SplMinHeap snippet echo?

php
<?php
$heap = new SplMinHeap();
$heap->insert(5);
$heap->insert(2);
$heap->insert(9);
echo $heap->extract();
?>
A
2
B
5
C
9
D
Notice
34

Question 34

Why is SplObjectStorage valuable for access-control layers that need to track permissions per object instance?

A
It lets you associate arbitrary metadata (such as scopes) with exact object references, so two instances of the same class can carry different access notes without array hashing collisions.
B
It serializes ACLs to XML automatically.
C
It enforces OAuth scopes out of the box.
D
It only works for Doctrine entities.
35

Question 35

Why do asset pipelines inspect SplFileInfo objects before copying binaries?

A
SplFileInfo exposes size, permissions, and realpath cheaply, letting pipelines skip redundant stat() calls and avoid copying unchanged files.
B
SplFileInfo decrypts binaries automatically.
C
SplFileInfo refuses to open directories.
D
Copy operations require SplFileInfo by specification.

QUIZZES IN PHP