nasumilu / iterators
A simple library which adds a fluent and functional interface to PHP Iterator(s).
v4.0.0
2024-04-28 14:49 UTC
Requires
- php: >=8.2
Requires (Dev)
- ext-pdo: *
- doctrine/dbal: 3.8.0
- phpunit/phpunit: ^10.4
README
Provides a fluent, functional interface to the PHP 8.2 iterable type.
Installation
composer require nasumilu/iterators
Basic Usage
Plain PHP Array
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
)
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());
Expected Output
Array
(
[2] => 9
[3] => 16
)
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
)