I am fairly new to PHP and just trying to convert something I did in C. The idiom for reading from a file in C that I was taught was:
while ((c = getchar()) != EOF) {
doSomethingWith(c);
}
I’ve done some reading and it would seem that the ‘right’ way to do this in PHP is:
while (!feof($file)) {
$c = fgetc($file);
doSomethingWith($c);
}
My question is: Is it ok to combine the two as follows (I have tried it, and its working ok on my test file), or are there situations where this could find a null before EOF?:
while (($c = fgets($f)) != null) {
doSomethingWith($c);
}
Cheers in advance
Steve
It’s ok, but the way you are doing it it’s wrong (at least "not correct at all").
fgets()returnsfalse, if the end of the file is reached, thus you should test againstfalseinstead. It works for you, because you use the "simple" equality operator (==), that will casenulltofalse, when comparing against a boolean.This means, it have to look like