PHP code example of jopic / php-streams

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

    

jopic / php-streams example snippets


Stream::ofList(array(1, 2, 3))
    ->limit(1) // limits the stream to the first element

Stream::ofList(array(1, 2, 3))
    ->skip(1) // the resulting elements are (2, 3)

Stream::ofList(array(1, 2, 3, 4, 5))
    ->step(function($i) { return $i + 2; }); // will iterate over the following elements (1, 3, 5)

Stream::ofList(array(1, 2, 3, 4, 5))
    ->filter(function($item) { return $item % 2 == 0; }); // will filter the elements (2, 4)

Stream::ofList(array(1, 2, 3))
    ->map(function($item) { return $item + 1; })
    ->toArray(); // will return the array(2, 3, 4)

Stream::ofList(array(1, 2, 3, 4, 5))
    ->filter(function($item) { return $item % 2 == 0; }) // matching elements (2, 4)
    ->reset(); // matching elements (1, 2, 3, 4, 5)

Stream::ofList(array(1, 2, 3, 4, 5))
    ->each(function($item) { echo $item; }); // will print all items

Stream::ofList(array(1, 2, 3, 4, 5))
    ->skip(2)
    ->limit(2)
    ->toArray(); // will return array(3, 4)

Stream::ofList(array(1, 2, 3))
    ->collect(','); // will return "1,2,3"

Stream::ofList(array(1, 2, 3))
    ->sum(); // will return 6

Stream::ofList(array(1, 2, 3))
    ->min(); // will return 1

Stream::ofList(array(1, 2, 3))
    ->max(); // will return 3

Stream::ofList(array(1, 2, 3, 4))
    ->avg(); // will return 2.5

Stream::ofList(array(1, 2, 3, 4, 5, 6))
    ->skip(1)
    ->filter(function($item) {
        return $item % 2 == 1;
    })
    ->limit(3)
    ->collect(', ') // will return "3, 5"

Stream::ofArray(array(
        "key1" => "value1",
        "key2" => 2,
        "key3" => 3,
        4 => "value 4"
    ))
    ->filter(function($key, $value) {
        return is_numeric($key);
    })
    ->toArray(); // will return array(4 => "value 4")