Reputation:
So I have this code set up like this
while(! feof($fn)) {
$result = fgets($fn);
// some code
}
How do I make it so it ignores the last line in the text file. My text file is set up so when something gets added it adds a new line afterwards. Doing it this way creates an error of an offset due to no data being put in for the last line.
I've already tried doing it so it adds a new line before the data, but then it creates another error because it'll have an offset with the first line being a break. (If more info is needed, I will edit question)
Upvotes: 0
Views: 567
Reputation: 57131
You could just add an extra condition to your code which checks the content read and skips the rest of the code in the loop if this is an empty line...
$result = fgets($fn);
if ( empty(trim($result)) ) {
continue;
}
This will also cope with empty lines at any point in the file as well.
Upvotes: 0
Reputation: 16741
With almost the same code you can ignore the last line:
while($result = fgets($fn)) {
if (!feof($fn)) {
// process all lines except the last one
}
}
fgets()
will return false
when no more lines can be read, so it acts like a kind of feof()
as well.
Upvotes: 1