Suppose I have the following recursive function to turn an array into a Generator:
function traverse(array $items): Generator {
if (!empty($items)) {
yield $items[0];
array_shift($items);
yield from traverse($items);
}
}
Running this function and iterating over the Generator through a foreach gives the expected result:
$values = traverse(['a', 'b', 'c', 'd', 'e']);
foreach ($values as $value) {
echo $value;
}
// 'abcde' is echoed
However, when I use the built-in function iterator_to_array(), I get the following result:
$values = iterator_to_array(traverse(['a', 'b', 'c', 'd', 'e']));
foreach ($values as $value) {
echo $value;
}
// Only 'e' is echoed
I would expect both pieces of code to behave identically, yet they don't. Why is their behavior different?
I am running this on PHP 8.1.