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

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

Feedback about page:

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


Type juggling and non-strict comparison issues:
* Reading from a file

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
46 Type juggling and non-strict comparison issues
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR