Skip to content

Instantly share code, notes, and snippets.

@copperwall
Last active March 18, 2018 17:46
Show Gist options
  • Save copperwall/906b77408abdfd103bd254151a927e29 to your computer and use it in GitHub Desktop.
Save copperwall/906b77408abdfd103bd254151a927e29 to your computer and use it in GitHub Desktop.
A array_filter alternative for iterables
<?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