PHP code example of rikudou / iterables

1. Go to this page and download the library: Download rikudou/iterables 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/ */

    

rikudou / iterables example snippets




use Rikudou\Iterables\Iterables;

$array = [1, 2, 3];

// built-in array_map
$mapped = array_map(fn (int $number) => $number ** 2, $array);
foreach ($mapped as $number) {
    echo $number, PHP_EOL;
}

$mapped = Iterables::map(fn (int $number) => $number ** 2, $array);
foreach ($mapped as $number) {
    echo $number, PHP_EOL;
}



use Rikudou\Iterables\Iterables;

// an iterable generator
$generator = function () {
    yield 1;
    yield 2;
    yield 3;
};

// array_map only works with an array, so we need to convert it to array first
$mapped = array_map(fn (int $number) => $number ** 2, iterator_to_array($generator()));

// the library version works directly with iterables
$mapped = Iterables::map(fn (int $number) => $number ** 2, $generator());



use Rikudou\Iterables\Iterables;
use Rikudou\Iterables\RewindableGenerator;

$keys = ['a', 'b', 'c'];
$values = [1, 2, 3];

// RewindableGenerator  {
    foreach ($generator as $key => $value) {
        echo "{$key} => {$value},", PHP_EOL;
    }
}



use Rikudou\Iterables\Iterables;
use Rikudou\Iterables\CacheableGenerator;

$keys = ['a', 'b', 'c'];
$values = [1, 2, 3];

// here we feed the raw generator directly as a parameter
$generator = new CacheableGenerator(Iterables::combine($keys, $values));

// let's iterate over the generator twice!
for ($i = 0; $i < 2; ++$i) {
    foreach ($generator as $key => $value) {
        echo "{$key} => {$value},", PHP_EOL;
    }
}