Topics Advanced PHP Features Generators & Iterators
advanced 14 min read

Generators & Iterators

Yield keyword, generator delegation, and the Iterator interface.

Generators

function rangeGenerator(int \$start, int \$end): Generator {
for (\$i = \$start; \$i <= \$end; \$i++) {
yield \$i;
}
}

foreach (rangeGenerator(1, 5) as \$num) {
echo \$num; // 1 2 3 4 5
}

Key-Value Yield

function mapGenerator(array \$items): Generator {
foreach (\$items as \$key => \$value) {
yield \$key => strtoupper(\$value);
}
}

Generator Delegation

function gen1(): Generator {
yield 1;
yield 2;
yield from [3, 4, 5]; // delegate
yield from gen2(); // delegate to another generator
}

IteratorAggregate

class MyCollection implements IteratorAggregate {
public function __construct(private array \$items) {}
public function getIterator(): Traversable {
return new ArrayIterator(\$this->items);
}
}

Examples

<?php
function fibonacci(int $limit): Generator {
    $a = 0; $b = 1;
    for ($i = 0; $i < $limit; $i++) {
        yield $a;
        [$a, $b] = [$b, $a + $b];
    }
}
foreach (fibonacci(10) as $n) echo $n . ' ';

Your Notes

Sign in to take notes for this lesson.

Quiz

Advanced PHP Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.