PHP code example of voltra / lazy-collection

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

    

voltra / lazy-collection example snippets


use LazyCollection\Stream;

Stream::registerMethod("mapTo42", static function(){
    /**
     * @var Stream $this
     */
    return $this->map(static function(){ return 42; });
});

Stream::fromIterable([1, 2, 3])
    ->mapTo42()
    ->toArray(); //-> [42, 42, 42]

Stream::registerFactory("answerToLife", function(){
    $gen = (static function(){
        yield 42;
    })();
    
    return new static($gen, false); // new static($generator, $isAssociative)
    
    /*
    Alternatively:
    
    return static:fromIterable([42]);
    */
});

Stream::answerToLife()->toArray(); //-> [42]

$items = [1, 2, 3, 4, 5, 6];
$results = [];

foreach($items as $item){
    $mapped = 3 * $item - 2; // models 3x-2
    if($mapped % 2 === 0)
        $results[] = $mapped;
}

$streamResults = Stream::fromIterable($items)
    ->map(function($x){ return 3 * $x - 2; })
    ->filter(function($x){ return $x % 2 === 0; })
    ->toArray();

// $results is the same as $streamResults