Skip to content

Instantly share code, notes, and snippets.

@CHH
Created November 7, 2012 14:26
Show Gist options
  • Save CHH/4031906 to your computer and use it in GitHub Desktop.
Save CHH/4031906 to your computer and use it in GitHub Desktop.
iterator_map function using Generators
<?php
function iterator_map(callable $callback)
{
$iterators = array_slice(func_get_args(), 1);
$multi = new MultipleIterator;
foreach ($iterators as $it) {
$multi->attachIterator($it);
}
foreach ($multi as $current) {
yield call_user_func_array($callback, $current);
}
}
$it = new ArrayIterator([0, 1, 2, 3]);
$it2 = new ArrayIterator(['zero', 'one', 'two', 'three']);
$map = iterator_map(
function($number, $word) {
return [$number, $word];
},
$it, $it2
);
foreach ($map as $val) {
var_dump($val);
}
@neitanod
Copy link

❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment