Skip to content

LookaheadIterator

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

Class LookaheadIterator.

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 in the iterable.

public count(): int

If the inner iterator implements Countable, it uses that. Otherwise, it counts the elements by iterating through them.

Return Value:

the number of elements in the iterable


Clone this wiki locally