Last active
March 18, 2018 17:46
-
-
Save copperwall/906b77408abdfd103bd254151a927e29 to your computer and use it in GitHub Desktop.
A array_filter alternative for iterables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
describe(strict_types = 1); | |
/** | |
* Like array_filter() but over an iterable, and it returns a new iterable with | |
* filtering instead of a filtered array. The callable, if non-null, should | |
* take arguments like iterator_map(). When the callable is null, null values | |
* will be filtered out (NOT falsey values, just x === null). | |
*/ | |
function iterator_filter(?callable $cb, iterable $itr): iterable { | |
$cb = $cb ?: function($x) { | |
return $x !== null; | |
}; | |
foreach ($itr as $key => $value) { | |
$keep = $cb($value, $key); | |
if ($keep) { | |
yield $value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment