Is there a way of doing array_map but as an iterator?
For example:
foreach (new MapIterator($array, $function) as $value)
{
if ($value == $required)
break;
}
The reason to do this is that $function is hard to calculate and $array has too many elements, only need to map until I find a specific value. array_map will calculate all values before I can search for the one I want.
I could implement the iterator myself, but I want to know if there is a native way of doing this. I couldn't find anything searching PHP documentation.
In short: No.
There is no lazy iterator mapping built into PHP. There is a non-lazy function iterator_apply(), but nothing like what you are after.
You could write one yourself, as you said. I suggest you extend IteratorIterator and simply override the current() method.
If there were such a thing it would either be documented here or here.
This is a lazy collection map function that gives you back an Iterator
:
/**
* @param array|Iterator $collection
* @param callable $function
* @return Iterator
*/
function collection_map( $collection, callable $function ) {
foreach( $collection as $element ) {
yield $function( $element );
}
}
I'm thinking of a simple Map class implementation which uses an array of keys and an array of values. The overall implementation could be used like Java's Iterator class whereas you'd iterate through it like:
while ($map->hasNext()) {
$value = $map->next();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With