Katsuke
Katsuke

Reputation: 575

SPLFileObject next() behavior

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.

Upvotes: 3

Views: 1568

Answers (2)

VolkerK
VolkerK

Reputation: 96159

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

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

Upvotes: 7

xarch
xarch

Reputation: 732

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

Upvotes: 1

Related Questions