Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP lazy array mapping

Tags:

php

spl

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.

like image 365
Ezequiel Avatar asked Jul 03 '11 23:07

Ezequiel


3 Answers

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.

like image 55
ezzatron Avatar answered Oct 17 '22 20:10

ezzatron


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 );
    }
}
like image 24
Jeroen De Dauw Avatar answered Oct 17 '22 20:10

Jeroen De Dauw


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();
  ...
}
like image 1
jerluc Avatar answered Oct 17 '22 21:10

jerluc