nasumilu/iterators

A simple library which adds a fluent and functional interface to PHP Iterator(s).

v4.3.1 2025-01-24 23:57 UTC

README

Provides a fluent, functional interface to the PHP 8.2 iterable type.

Installation

composer require nasumilu/iterators

Basic Usage

Plain Old PHP Array

Example which uses a plain old php array for the iterable values.

use Nasumilu\Iterators\Iterators;

$iterator = Iterators::from([1, 2, 3, 4])
    ->map(static fn(int $value): int => $value ** 2)
    ->filter(static fn(int $value): bool => $value >= 9);

print_r($iterator->values());

Expected Output

Array
(
    [2] => 9
    [3] => 16
)

By default, the terminating FunctionalIterator::values preserves the offset and gathers the values into an unsorted array.

PHP Iterators & IteratorAggregate

Example One

Any iterable type maybe used, in this example instead of an array the FunctionalIterator is constructed using the built-in ArrayIterator.

use \ArrayIterator;
use Nasumilu\Iterators\Iterators;

$values = new ArrayIterator([1, 2, 3, 4]);
$iterator = Iterators::from($values)
    ->map(static fn(int $value): int => $value ** 2)
    ->filter(static fn(int $value): bool => $value >= 9);

print_r($iterator->values(preserve_keys: false));

Expected Output

Array
(
    [0] => 9
    [1] => 16
)

Similar to the previous example the terminating FunctionalIterator::filter returns the values determined by the predicate callable, except the original offset are no longer preserved.

Example Two

Since any class which implements the ArrayAggregate interface will provide an interable type, they too may also be used to construct a FunctionalInterator.

use \ArrayObject;
use Nasumilu\Iterators\Iterators;

$values = new ArrayObject([1, 2, 3, 4]);
$iterator = Iterators::from($values)
    ->map(static fn(int $value): int => $value ** 2)
    ->filter(static fn(int $value): bool => $value >= 9);

print_r($iterator->values(static fn(int $a, int $b): int => $a <=> $b, false));
print_r($iterator->values(static fn(int $a, int $b): int => $b <=> $a, false));

Expected Output

Array
(
    [0] => 9
    [1] => 16
)
Array
(
    [0] => 16
    [1] => 9
)

It is also possible to sort the values by passing a callable which is accepted by the built-in usort function. Seen in the example the values are first sorted ascending, then descending without preserving the original offsets.

Learn More