On 21/12/12 10:34, Christopher Jones wrote:


On 12/20/2012 08:31 AM, Larry Garfield wrote:
On 12/19/12 10:30 PM, Christopher Jones wrote:


On 12/19/2012 03:18 PM, Larry Garfield wrote:
You could likely simplify the code even further using an infinite
iterator:

http://us1.php.net/infiniteiterator

$result = preg_replace_callback(
     '/word/',
     function($matches) use (&$replacements_iterator) {
         return $replacements->next();
     },
     'word word word word word'
);

--Larry Garfield


What am I missing that causes the first call to
$replacements_iterator->current() to return NULL
unless the iterator is rewound before use?

Eh, nothing. You're right, next() doesn't return an element, it just advances, so you still need the current() call. Which seems kinda silly to me, but whatev.

That is documented, so it's OK. The curiosity (bug?) is the need to call rewind():

$replacements_iterator = new InfiniteIterator(new ArrayIterator($replacements));
$replacements_iterator->rewind();  // why is the rewind needed?

$result = preg_replace_callback(
    '/word/',
    function($matches) use ($replacements_iterator) {
        $r = $replacements_iterator->current();
        $replacements_iterator->next();
        return $r;
    },
    'word word word word word word word word'
);

In other (simple) scripts using InfiniteIterator the rewind wasn't needed.




What happens if you do:
$replacements_iterator = new InfiniteIterator(new ArrayIterator($replacements));
var_dump($replacements_iterator->current());

If I remember correctly, when you pass a traversable into foreach, under the hood, it basically calls:

$iterator->rewind();
while($iterator->valid()){
    $value = $iterator->current();
    ....(foreach block)....
    $iterator->next();
}

So that might explain why it works in "(simple) scripts".

It does seem like a bug that the rewind is required though. A newly created iterator should already be in a rewound state so the call shouldn't be needed.

Cheers,
David

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to