Be aware of the proper methods to iterate the specific Iterator you are consuming, as the implementation of the method could vary its behaviour.
For example, unlike the ArrayIterator, you can't iterate on a SplDoubleLinkedList with current() without using next() on every iteration (and then, only would iterate if you return true at the end of the callable. It is far easier then with LinkedLists use a while($it->valid()) { $it->current(); $it->next(); }
Let's see:
<?php
$ll = new \SplDoublyLinkedList();
$ll->push('ze');
$ll->push('ome');
$ll->push('yei');
$ll->push('nahui');
$ll->rewind();
$iterations_done = iterator_apply($ll, function(Iterator $it) {
echo implode("\t=>", [
$it->key(),
$it->current(),
ucfirst($it->current())
]),"\n";
return true;
}, array($ll));
echo "Did iterate {$iterations_done} times \n";
$ll->rewind();
$iterations_done = iterator_apply($ll, function(Iterator $it) {
echo implode("\t=>", [
$it->key(),
$it->current(),
ucfirst($it->current())
]),"\n";
$it->next();
return true;
}, array($ll));
echo "Did iterate {$iterations_done} times \n";
$ll->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);
var_dump($ll->count());
foreach($ll as $key => $val) {
echo "{$key}\t",ucfirst($val),"\n";
}
var_dump($ll->count());
?>
Output:
0 =>ze =>Ze
0 =>ze =>Ze
0 =>ze =>Ze
0 =>ze =>Ze
Did iterate 4 times
0 =>ze =>Ze
1 =>ome =>Ome
2 =>yei =>Yei
3 =>nahui =>Nahui
Did iterate 4 times
int(4)
0 Ze
0 Ome
0 Yei
0 Nahui
int(0)