In PHP, SPLFileObject allows you to process files as iterators.
But there is behavior that I do not understand. When you call next () on an 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 indicate that key () returns the current line number.
Code to play:
test.txt
0
1
2
3
iterator.php
<?php
$fi = new SPLFileObject('test.txt');
echo $fi->current() . "\n";
echo $fi->key() . "\n";
$fi->next();
$fi->next();
$fi->next();
echo $fi->current() . "\n";
echo $fi->key() . "\n";
From what I see, the following does not work on this section. It will advance if I use it as follows:
iterator_fix.php
<?php
$fi = new SPLFileObject('test.txt');
echo $fi->current() . "\n";
echo $fi->key() . "\n";
$fi->next();
$fi->current();
$fi->next();
$fi->current();
$fi->next();
echo $fi->current() . "\n";
echo $fi->key() . "\n";
Can someone explain if this is a mistake or if this is the alleged behavior?
Looked at google and php forums and nothing came up. Thanks in advance.
source
share