# MultipleIterator, add a default value

- Thread: https://externals.io/message/67424
- Original archive: https://news-web.php.net/php.internals/67424
- Started by Ivan Enderlin @ Hoa on 2013-05-14T08:35:48+00:00
- Messages: 1
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #67424 — Ivan Enderlin @ Hoa — 2013-05-14T08:35:48+00:00

URL: https://externals.io/message/67424#67424

Hi internals,

I propose to ameliorate the MultipleIterator class.

When a MultipleIterator instance has the MIT_NEED_ANY flag, and when one 
of the attached iterators has reached its end, the returned value is 
NULL. I propose to change this behavior by allowing a different default 
value.

Example with no default value:

     $it = new \MultipleIterator(
         \MultipleIterator::MIT_NEED_ANY
       | \MultipleIterator::MIT_KEYS_ASSOC
     );
     $it->attachIterator(new \ArrayIterator(['a', 'b', 'c']), 'foo');
     $it->attachIterator(new \ArrayIterator(['x']),           'bar');

     foreach($it as $value)
         echo $value['foo'], ' => ', $value['bar'], "\n";

     /**
      * Will output:
      *     a => x
      *     b =>
      *     c =>
      */

Example with 42 as a default value (given as a third parameter of the 
MultipleIterator::attachIterator method):

     $it->attachIterator(new \ArrayIterator(['a', 'b', 'c']), 'foo', 42);
     $it->attachIterator(new \ArrayIterator(['x']),           'bar', 42);

     foreach($it as $value)
         echo $value['foo'], ' => ', $value['bar'], "\n";

     /**
      * Will output:
      *     a => x
      *     b => 42
      *     c => 42
      */

It is clearly useful when one of the iterators returns an array, used 
directly in a loop. To avoid a "NULL pointer exception", we can specify 
an empty array as a default value.

A PHP implementation is pretty easy to do. Naively, we are able to write 
https://github.com/hoaproject/Iterator/commit/59dcff7f331a7338644cf9a8965d2a934a38661e.

If you think it can be useful, I propose to write a RFC with a patch.

Thoughts?

-- 
Ivan Enderlin
Developer of Hoa
http://hoa-project.net/

PhD. student at DISC/Femto-ST (Vesontio) and INRIA (Cassis)
http://disc.univ-fcomte.fr/ and http://www.inria.fr/

Member of HTML and WebApps Working Group of W3C
http://w3.org/
