When reading from a file, we want to be able to know when we've reached the end of that file. Knowing that fgets()
returns false at the end of the file, we might use this as the condition for a loop. However, if the data returned from the last read happens to be something that evaluates as boolean false
, it can cause our file read loop to terminate prematurely.
$handle = fopen ("/path/to/my/file", "r");
if ($handle === false) {
throw new Exception ("Failed to open file for reading");
}
while ($data = fgets($handle)) {
echo ("Current file line is $data\n");
}
fclose ($handle);
If the file being read contains a blank line, the while
loop will be terminated at that point, because the empty string evaluates as boolean false
.
Instead, we can check for the boolean false
value explicitly, using strict equality operators:
while (($data = fgets($handle)) !== false) {
echo ("Current file line is $data\n");
}
Note this is a contrived example; in real life we would use the following loop:
while (!feof($handle)) {
$data = fgets($handle);
echo ("Current file line is $data\n");
}
Or replace the whole thing with:
$filedata = file("/path/to/my/file");
foreach ($filedata as $data) {
echo ("Current file line is $data\n");
}