IterableIterator

Class
Final: Yes

A normalized iterator wrapper that ensures any iterable (array or Traversable) is treated as a standard \Iterator.

Description

This utility class simplifies iterator interoperability by converting arrays into \ArrayIterator and wrapping \Traversable instances as needed. It SHALL be used when an \Iterator is expected but the input MAY be any iterable.

Example usage:

$items = new IterableIterator([1, 2, 3]);

foreach ($items as $item) {
    echo $item;
}
// Output: 123
Tags
since
1.1.0

Table of Contents

Methods

__construct()

Constructs an IterableIterator from any iterable input.

 : mixed
count()

Counts the number of elements exposed by the inner iterator.

 : int
Methods

__construct()

Public

Constructs an IterableIterator from any iterable input.

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

Description

Arrays are converted to \ArrayIterator; Traversables are passed directly.

Parameters
$iterable : iterable<string|int, mixed>

Description

the iterable to wrap as an \Iterator

count()

Public

Counts the number of elements exposed by the inner iterator.

public count() : int

Description

If the inner iterator implements 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 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 values
int

Description

the total number of elements available from the inner iterator