Twifty
Twifty

Reputation: 3378

Last foreach item when using a generator

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?

Upvotes: 3

Views: 1681

Answers (1)

Timurib
Timurib

Reputation: 2743

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";
}

Upvotes: 3

Related Questions