tags:

views:

186

answers:

2

Hi there,

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.

+1  A: 

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

$fi = new SPLFileObject('test.txt');
$fi->setFlags(SPLFileObject::READ_AHEAD);
VolkerK
Thanks for that explanation, is there any reason why that is not default behavior?I mean, the documentation talks about key() referring to the line number. So if i don't set that flag manually the key will be referring to some sort of internal counter?
Katsuke
+1  A: 

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

xarch
Using next() is the most direct way I can find to skip lines on the file. I'm not using the file with 'foreach', I'm using 'while', cause i have to consume variable amounts of lines at any given time depending on the report file. Some of this variable lines are skippable. VolkerK solution fits my scenario. I'm just still wondering why that flag is not the default behavior which contradicts the documentation about key().
Katsuke