Skip to content

Samples

lasso edited this page Nov 30, 2016 · 4 revisions

If you have not done so already, please have a look at the basics page.

Enumerable code samples

All code samples below will use the same Enumerable class

use Lasso3000\Enumerable;

class MyEnumerable {
    use Enumerable;

    protected function __each()
    {
        yield 'FIRST';
        yield 'SECOND';
        yield 'THIRD';
    }
}

Example 1: Use each to run a callback against every element

$myEnum = new MyEnumerable();

// You can use a built-in function
$myEnum->each('var_dump');

// Prints string(5) "FIRST" string(6)\n"SECOND" string(5)\n"THIRD"\n on the console

// or define your own using a closure
$myEnum->each(
    function($elem)
    {
        echo strrev($elem);
    }
);

// Prints TSRIFDNOCESDRIHT on the the console

Example 2: Use map to run a callback against every element and return the result

$myEnum = new MyEnumerable();

// You can use a built-in function
$enumArray = $myEnum->map('strtolower');

// $enumArray is an EnumerableArray containing all elements lowercased. You can convert
// the EnumerableArray into an ordinary array by using the toArray method

$arr = $enumArray->toArray();

// $arr contains ['first', 'second', 'third']

You can read more about the EnumerableArray class on the basics page.

Example 3: Use findAll to return all elements matching a criteria

$myEnum = new MyEnumerable();

// Find all elements with fewer than six characters
$enumArray = $myEnum->findAll(function($elem) { return strlen($elem) < 6; });

// Returns an EnumerableArray containing 'FIRST' and 'THIRD'

Exammple 4: Use reject to return all elements not matching a criteria

$myEnum = new MyEnumerable();

// Find all elements with more than five characters
$enumArray = $myEnum->reject(function($elem) { return strlen($elem) < 6; });

// Returns an EnumerableArray containing 'SECOND'