Created
November 7, 2012 14:26
-
-
Save CHH/4031906 to your computer and use it in GitHub Desktop.
iterator_map function using Generators
This file contains hidden or 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 | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
❤️