php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #55136 Code sample is wrong
Submitted: 2011-07-05 09:52 UTC Modified: 2011-07-05 10:20 UTC
From: rp_joe at yahoo dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: Irrelevant OS: xp
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: rp_joe at yahoo dot com
New email:
PHP Version: OS:

 

 [2011-07-05 09:52 UTC] rp_joe at yahoo dot com
Description:
------------
---
From manual page: http://www.php.net/function.fgets%23Examples
---
This code sample is wrong!
  while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
When the `!== false` is used it returns a value, whether the function failed or not. In this example $buffer will be 1 or 0. 
 

Test script:
---------------
 while ($buffer = fgets($handle, 4096))  {
        echo $buffer;
    }

Expected result:
----------------
I expect to see a line of text read from the file and echoed.  

Actual result:
--------------
0 or 1 is echoed. 

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-07-05 10:20 UTC] RQuadling@php.net
-Status: Open +Status: Bogus
 [2011-07-05 10:20 UTC] RQuadling@php.net
$buffer is assigned a value from fgets(). If that value is not false (both in type 
and in value), then $buffer is displayed. fgets() cannot assign a boolean false 
for valid data. false indicates a failure of some sort or end of file.

Due to type juggling, '' and 0 can both be juggled to false and therefore would 
cause the while loop to abort, not printing $buffer. Therefore, !== is used to 
enforce both the value and the type during the comparison.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 09 16:02:26 2025 UTC