Reading from a file

suggest change

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);

A blank line is "\n", which is truthy, so the loop does not stop there. It does stop when fgets() returns "0" with no trailing newline, because that string is falsy. A last line "0\n" is truthy.

Check for boolean false explicitly, using strict equality:

while (($data = fgets($handle)) !== false) {
    echo ("Current file line is $data\n");
}

The !== false loop is the one that keeps every line. This feof() loop runs one extra time. After the last line, feof() is still false until a read fails, so fgets() returns false and that value is echoed:

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");
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents