PHP code example of loophp / iterators

1. Go to this page and download the library: Download loophp/iterators library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

loophp / iterators example snippets




// Generator
$generator = static function (): \Generator {
    yield true => 'foo';
    yield false => 'bar';
    yield ['foo', 'bar'] => 'foobar';
};

$iterator = new CachingIteratorAggregate($generator());

foreach ($iterator as $key => $value); // This will work.
foreach ($iterator as $key => $value); // This will also work.



$iterator = (new ChunkIterableAggregate(
    range('a', 'j'),
    2
));

foreach ($iterator as $chunk) {} // ['a', 'b'], ['c', 'd'], ...



$iterator = (new FilterIterableAggregate(
    range(0, 5),
    static fn (int $v, int $key, iterable $iterable): bool =>
        0 === (($v + 2 * $key + count($iterable)) % 2)
));

foreach ($iterator as $filteredValue) {} // 0, 2, 4



// Generator
$naturals = static function () {
    $i = 0;

    while (true) {
        yield $i++;
    }
};

$iterator = new InterruptableIterableIteratorAggregate($generator());

foreach ($iterator as $generator => [$key, $value]) {
    var_dump($value);

    if (10 === $value) {
        $generator->send(InterruptableIterableIteratorAggregate::BREAK);
    }
}



$iterator = (new MapIterableAggregate(
    range('a', 'c'),
    static fn (string $letter, int $key, iterable $iterable): string =>
        sprintf(
            '%s::%s::%s',
            $key,
            $letter,
            gettype($iterable)
        )
));

foreach ($iterator as $tranformedValue) {}



$rngGenerator = (new MersenneTwisterRNGIteratorAggregate())
    ->withMin(1)
    ->withMax(10)
    ->withSeed($seed);

foreach ($rngGenerator as $randomValue) {} // Random integers in [1, 10]



// Generator
$generator = static function (): \Generator {
    yield true => 'foo';
    yield false => 'bar';
    yield ['foo', 'bar'] => 'foobar';
};

$iterator = new PackIterableAggregate($generator());

foreach ($iterator as $value);
/*
$value will yield the following values:

- [true, 'foo']
- [false, 'bar']
- [['foo', 'bar'], 'foobar']
*/



$generator = static function(): Generator {
    while (true) {
        yield mt_rand(0, 9);
    }
};

$iterator = new UniqueIterableAggregate($generator(), 1000);

foreach ($iterator as $value) {} // 9 random values only.



// Generator
$generator = static function (): \Generator {
    yield [true, 'foo'];
    yield [false, 'bar'];
    yield [['foo', 'bar'], 'foobar'];
};

$iterator = new UnpackIterableAggregate($generator());

foreach ($iterator as $key => $value);
/*
$key and $value will yield the following values:

- true => 'foo'
- false => 'bar'
- ['foo', 'bar'] => 'foobar'
*/



$callable = static fn (int $from, int $to) => yield from range($from, $to);

$iterator = new ClosureIterator($callable(10, 20));



$iterator = new IterableIterator(range(1, 10));



$inputIterator = new ArrayIterator(range('a', 'e'));
$iteratorAggregate = new PausableIteratorAggregate($inputIterator);

$i = 0;
foreach ($iteratorAggregate as $v) {
    var_dump($v) // Print: 'a', 'b', 'c'
    if (++$i === 2) {
        break;
    }
}

foreach ($iteratorAggregate->rest() as $v) {
    var_dump($v) // Print: 'd', 'e'
}



$seed = random_int(0, 1000);
$inputIterator = new ArrayIterator(range('a', 'e'));
$iterator = new RandomIterableAggregate($inputIterator, $seed);

foreach ($iterator as $v) {
    var_dump($v);
}

$iterator = new CachingIteratorAggregate(
    (new RandomIterableAggregate($inputIterator, $seed))->getIterator()
);

foreach ($iterator as $v) {
    var_dump($v);
}
foreach ($iterator as $v) {
    var_dump($v);
}



$treeStructure = [
    [
        'value' => '1',
        'children' => [
            [
                'value' => '1.1',
                'children' => [
                    [
                        'value' => '1.1.1',
                        'children' => [],
                    ],
                ],
            ],
            [
                'value' => '1.2',
                'children' => [],
            ],
        ],
    ],
    [
        'value' => '2',
        'children' => [],
    ],
];

$iterator = new RecursiveIterableAggregate(
    $treeStructure,
    fn (array $i) => $i['children']
);

foreach ($iterator as $item) {
    var_dump($item['value']); // This will print '1', '1.1', '1.1.1', '1.2', '2'
}



$iterator = (new ReductionIterableAggregate(
    range(0, 10),
    static fn (int $carry, int $value, int $key, iterable $iterable): int => $carry + $value,
    0
));

foreach ($iterator as $reduction) {} // [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

$valueObjectFactory = static fn (int $id, int $weight): object => new class($id, $weight)
{
    public function __construct(public readonly int $id, public readonly int $weight) {}
};

$input = [
    $valueObjectFactory(id: 1, weight: 1),
    $valueObjectFactory(id: 2, weight: 1),
    $valueObjectFactory(id: 3, weight: 1),
];

$sort = new SortIterableAggregate(
  $input,
  static fn (object $a, object $b): int => $a->weight <=> $b->weight
);