Question

In PHP SPLFileObject allows treating files as iterators.

Yet there is a behavior that I don't understand. When you call next() on the object it increments the value of key() but does not advance the line in the file unless you call current() with each iteration. The SPL docs state that key() returns current line number.

Code to reproduce:

test.txt

0
1
2
3

iterator.php

<?php
$fi = new SPLFileObject('test.txt');
echo $fi->current() . "\n"; // prints 0
echo $fi->key() . "\n"; //prints 0
$fi->next();
$fi->next();
$fi->next();
echo $fi->current() . "\n"; // prints 1, expecting 3
echo $fi->key() . "\n"; //prints 3

From what i can see, the next is not working on this section. It will advance if i use it this way:

iterator_fix.php

<?php
$fi = new SPLFileObject('test.txt');
echo $fi->current() . "\n"; // prints 0
echo $fi->key() . "\n"; //prints 0
$fi->next();
$fi->current();
$fi->next();
$fi->current();
$fi->next();
echo $fi->current() . "\n"; // prints 3 as expected
echo $fi->key() . "\n"; //prints 3

Could anyone explain if this is a bug or if it is intended behavior?

Looked over google and php forums and nothing came up. Thanks in advance.

Was it helpful?

Solution

SPLFileObject::next() only has an effect if the READ_AHEAD flag has been set.

$fi = new SPLFileObject('test.txt');
$fi->setFlags(SPLFileObject::READ_AHEAD);

OTHER TIPS

Well, in any case, why don't you use it with foreach, as it's what it's intended for?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top