Reputation: 1821
I have a text file that I want to read line by line. For each line I also need the value from the next line, so I need something to read the next line while in the current line.
I have read through many answers here that I can do this with a foreach
loop, but it requires reading the whole file in ahead. I am looking for something to only read as needed.
Here is what I got so far with SplFileObject.
$file = new \SplFileObject($textFile);
$lastNumber = 500;
while (!$file->eof()) {
$currentLine = $file->fgets();
$currentNumber = intval($currentLine);
$file->next();
if ($file->eof()) {
$nextNumber = intval($lastNumber);
} else {
$nextNumber = intval($file->fgets()) - 1;
}
echo $currentNumber . ', ' . $nextNumber . '<br>';
}
Suppose I have a text that have lines like this
0
100
200
300
400
I want them to print out like this
0, 99
100, 199
200, 299
300, 399
400, 500
But my code was skipping every other line
0, 99
200, 299
400, 500
My guess is that my while loop and the $file->next()
each moves the line by 1 every loop, that's why the skip. But without the next()
call, I don't know how to get the value of the next line. How do I fix this?
Upvotes: 0
Views: 251
Reputation: 4394
Use this PHP Code Solution.
$textFile = 'text.txt';
$file = new SplFileObject($textFile);
$lastNumber = 500;
foreach ($file as $lineNumber => $line) {
$currentNumber = intval($file->current());
if ($lineNumber === 0) {
$previousNumber = $currentNumber;
continue;
} else {
$nextNumber = $currentNumber - 1;
echo $previousNumber . ', ' . $nextNumber . '<br>';
$previousNumber = $currentNumber;
if ($file->eof()) {
$nextNumber = intval($lastNumber);
echo $currentNumber . ', ' . $nextNumber . '<br>';
}
}
}
Upvotes: -1