InterleaveIteratorIterator

Class

Interleaves elements from multiple iterators in a round-robin fashion.

Description

This iterator alternates between multiple traversable sources, returning one element from each before cycling back to the first. The iteration stops once all iterators are exhausted.

Usage Example:

Tags
example

Description

Interleaving two iterators

use FastForward\Iterator\InterleaveIteratorIterator;
use ArrayIterator;

$dataSetOne = new ArrayIterator([1, 3, 5]);
$dataSetTwo = new ArrayIterator([2, 4, 6]);

$interleavedIterator = new InterleaveIteratorIterator($dataSetOne, $dataSetTwo);

foreach ($interleavedIterator as $value) {
    echo $value . ' '; // Outputs: 1 2 3 4 5 6
}

Note: The iterator stops once all sources are exhausted.

since
1.0.0

Table of Contents

Properties

 : array<int, Iterator>
 : int

Methods

__construct()

Initializes the InterleaveIteratorIterator.

 : mixed
count()

Counts the number of elements available in the iterator.

 : int
current()

Retrieves the current element from the active iterator.

 : mixed
key()

Retrieves the current key from the active iterator or a normalized sequential key.

 : string|int
 : void
 : void
valid()

Checks if at least one iterator still has elements.

 : bool
Properties

$position

Private
private int $position = 0

Description

the normalized sequential numeric key for yielded values without string keys

Methods

__construct()

Public

Initializes the InterleaveIteratorIterator.

public __construct( iterable<string|int, mixed>  ...$iterators) : mixed
Parameters
$iterators : iterable<string|int, mixed>

Description

The iterators to be interleaved.

Tags
throws
InvalidArgumentException

Description

if no iterators are provided

count()

Public

Counts the number of elements available in the iterator.

public count() : int

Description

This method MUST count the elements by iterating over a clone of the current iterator instance so that the active iterator state of the original object is not modified during the counting process. Concrete implementations SHOULD therefore remain safely cloneable whenever this behavior is expected to be used.

Return values
int

Description

the total number of elements exposed by the iterator

current()

Public

Retrieves the current element from the active iterator.

public current() : mixed
Return values

Description

the current element

key()

Public

Retrieves the current key from the active iterator or a normalized sequential key.

public key() : string|int

Description

If the active iterator's current key is a string, it is returned directly. Otherwise, a normalized sequential numeric key is returned based on the position of yielded values without string keys.

Return values
string|int

Description

the current key

valid()

Public

Checks if at least one iterator still has elements.

public valid() : bool
Return values
bool

Description

true if there are remaining elements, false otherwise