php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51422 invalid result
Submitted: 2010-03-29 05:42 UTC Modified: 2010-03-29 05:49 UTC
From: ssiangge at yahoo dot com dot sg Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 5.2.13 OS: Win 7, Ubuntu 9.10
Private report: No CVE-ID: None
 [2010-03-29 05:42 UTC] ssiangge at yahoo dot com dot sg
Description:
------------
When I want test the value(int 0) is or is not match with a string(string "text"), it return true! By right it should return false. Then I try on other value, it also return wrong result!

Test script:
---------------
<?php

  $question = true;
  if ("text" == $question) echo "text == $question => true<br />";
  else echo "text == $question => false<br />";

  $question = 0;
  if ("text" == $question) echo "text == $question => true<br />";
  else echo "text == $question => false<br />";

  $question = 1;
  if ("text" == $question) echo "text == $question => true<br />";
  else echo "text == $question => false<br />";

  $question = false;
  if ("text" == $question) echo "text == $question => true<br />";
  else echo "text == $question => false<br />";
  
?>

Expected result:
----------------
text == 1 => false
text == 0 => false
text == 1 => false
text == => false


Actual result:
--------------
text == 1 => true
text == 0 => true
text == 1 => false
text == => false


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-03-29 05:47 UTC] ssiangge at yahoo dot com dot sg
-Status: Open +Status: Closed
 [2010-03-29 05:47 UTC] ssiangge at yahoo dot com dot sg
I found answer from the user manual...
hmmm....

#
If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement. 
#

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true

switch ("a") {
case 0:
    echo "0";
    break;
case "a": // never reached because "a" is already matched with 0
    echo "a";
    break;
}
?>
 [2010-03-29 05:49 UTC] rasmus@php.net
-Status: Closed +Status: Bogus
 [2010-03-29 05:49 UTC] rasmus@php.net
That's what the === operator is for.  == will do type conversion.  A non-zero 
non-empty string evaluates to true.  This is well-documented at

http://php.net/manual/en/language.operators.comparison.php
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 10 19:01:34 2025 UTC