Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Stealth Generator

By Frederic Bouchery

<?php 

function foo(): iterable {
    return ['a'];
    yield 'b';
}

foreach(foo() as $v) {
    echo $v;
}

The code below has a useless loop. The presence of the yield keyword in the function body makes it a generator. As such, foreach() will react to yield calls, though the function returns immediately, without a yield. Hence, the empty loop, even though the function returns an array: indeed, to have the function behave as expected, it is necessary to remove the unreachable yield call, and then, the foreach() can use the return for the loop.

See Also

PHP Features

Last updated: 10 September 2026