Skip to content

LookaheadIterator

github-actions edited this page Mar 31, 2026 · 3 revisions

An iterator that allows peeking at the next value(s) and stepping back to the previous value(s) without advancing the iteration.

This iterator extends IteratorIterator and provides methods peek() and prev() to inspect the next and previous values without modifying the current iteration state.

Usage Example:


Methods

__construct

Initializes the LookaheadIterator.

public __construct(iterable $iterator): mixed

Parameters:

Parameter Type Description
$iterator iterable the iterator to wrap

lookAhead

Retrieves the next value(s) without advancing the iterator.

public lookAhead(int $count = 1): mixed

If $count is specified, an array of the next $count values will be returned.

Parameters:

Parameter Type Description
$count int the number of upcoming values to peek at (default: 1)

Return Value:

the next value, an array of upcoming values, or null if no further elements exist

Throws:

if $count is less than 1


lookBehind

Retrieves the previous value(s) without moving the iterator backward.

public lookBehind(int $count = 1): mixed

If $count is specified, an array of the previous $count values will be returned.

Parameters:

Parameter Type Description
$count int the number of previous values to retrieve (default: 1)

Return Value:

the previous value, an array of previous values, or null if no previous elements exist

Throws:

if $count is less than 1


next

Advances the iterator and updates the internal position counter.

public next(): void

This method increments the internal position tracker and moves the iterator forward.


rewind

Resets the iterator to the first available element.

public rewind(): void

This method rewinds both the main iterator and the peeking iterator, ensuring that both are in sync when restarting the iteration.


Inherited methods

count

Counts the number of elements exposed by the inner iterator.

public count(): int

If the inner iterator implements

  • See: \Countable, this method SHALL return the value provided by that implementation. Otherwise, it MUST count elements by iterating over the iterator. If the inner iterator is not cloneable, this method SHALL wrap the current object in an

  • See: \IteratorIterator instance and count through that wrapper to avoid performing an invalid clone operation. If the inner iterator is cloneable, this method SHOULD count over a clone so that the original iterator state is preserved as much as possible.

Return Value:

the total number of elements available from the inner iterator


Clone this wiki locally