iterable, yield)The iterable pseudo-type accepts any array or object implementing the Traversable interface (such as ArrayIterator or Generator). Generators provide a simple, memory-efficient way to iterate over large datasets without building arrays in memory using the yield keyword.
| Feature | Standard Array | Generator (yield) |
|---|---|---|
| Memory Allocation | Loads all elements into RAM at once | Computes and yields 1 element at a time on demand |
| Performance | Crashes on multi-gigabyte files/datasets | Uses constant low RAM memory footprint (~1KB) |
| Data Access | Random indexed access ($arr[5]) |
Sequential iteration only (foreach) |
flowchart TD
A["foreach (readLargeFile() as $line)"] --> B["Generator Called"]
B --> C["Reads 1 Line from File"]
C --> D["yield $line (Pausable Execution)"]
D --> E["Loop Processes Single Line"]
E -->|Fetch Next| B
<?php
declare(strict_types=1);
// Generator Function yielding numbers lazily
function rangeGenerator(int $start, int $end): Generator
{
for ($i = $start; $i <= $end; $i++) {
// yield pauses function execution and returns single value
yield $i;
}
}
// Function accepting 'iterable' pseudo-type (Accepts both arrays & generators!)
function processCollection(iterable $items): void
{
$sum = 0;
foreach ($items as $item) {
$sum += $item;
}
echo "Total Collection Sum: $sum
";
}
// Processing array vs generator seamlessly
$arrayCollection = [10, 20, 30];
$generatorCollection = rangeGenerator(1, 100);
processCollection($arrayCollection);
processCollection($generatorCollection);
echo "Memory Usage with Generator: " . round(memory_get_usage() / 1024, 2) . " KB
";
iterable Type Hints for Flexible Methods: Type-hint iterable when a method needs to loop over data regardless of whether it receives an array or generator.yield fgets($handle) when parsing huge log files to maintain minimal RAM usage.Write a generator function evenNumbers(int $max): Generator that uses yield to return all even numbers up to $max!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.