0

The PHP Iterator::key page says:

Return Values:

Returns scalar on success, or NULL on failure.

but in order to be able to decide from within the iterator logic whether the current iterator node is valid or not (so as to be able to return null or something else) from within Iterator::key, one must call Iterator::check(). Hence it seems natural to me that most people would then call Iterator::check() from within Iterator::next() so that it can set the return value of 'Iterator::key()` to null if the current iterator position is invalid.

But this leads to Iterator::check() being called twice when a foreach loop is run. How can I get rid of such redundancy?

John Sonderson
  • 3,238
  • 6
  • 31
  • 45

1 Answers1

0

To solve the problem it is sufficient to introduce a $currentNodeChecked boolean variable, which can be checked before calling Iterator::check().

John Sonderson
  • 3,238
  • 6
  • 31
  • 45