How does yield from let a generator delegate part of its iteration to another generator or an array, and why is this useful?
Short answer
The yield from construct lets a generator delegate to another iterable, such as a different generator function or a plain array, effectively flattening that iterable's values into the outer generator's own sequence of yielded values, which is useful for composing several smaller…
Advertisement
AModel answer
The yield from construct lets a generator delegate to another iterable, such as a different generator function or a plain array, effectively flattening that iterable's values into the outer generator's own sequence of yielded values, which is useful for composing several smaller generators together into a larger, combined sequence without needing to manually loop over and re yield each individual value from the nested source.
function letters() {
yield 'a';
yield 'b';
}
function combined() {
yield from letters();
yield 1;
yield 2;
}
foreach (combined() as $value) {
echo $value;
}Real-world example
A data processing pipeline combines several smaller specialized generators together using yield from, building one larger unified sequence out of multiple smaller, independently reusable pieces of iteration logic.
Likely follow-ups
- Can yield from delegate to a plain array as well as another generator?
- How does yield from affect what value is returned to the outer code from the return statement of the inner generator?
Related topics