Usually, before entering a foreach loop, we would call reset or end to find the first or last item in an array. But, this doesn't play well with generators, especially those which are memory intensive. The simple solution would be to use iterator_to_array. Again, not the ideal solution. It requires copying the whole output to memory and a second iteration.
Checking for the first item could be done by setting a simple bool before the loop. But what about the last item? With access to the class which supplies the generator, I can implement the \Countable interface to get the number of expected iterations. That only works IF I have access, sometimes it may be third party and cannot be modified.
How can I detect the last iteration of a generator loop without having to loop through beforehand?
In the while loop you can manually check a generator state by the additional call of valid() method:
function g() {
for ($i = 0; $i < 10; ++$i) {
yield $i;
}
}
$g = g();
while ($g->valid()) {
echo "Value ", $g->current();
$g->next();
echo $g->valid() ? " is not last\n" : " is last\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With