CodeIgniter Forums
Why is this true? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Why is this true? (/showthread.php?tid=32546)



Why is this true? - El Forum - 07-27-2010

[eluser]Steven Ross[/eluser]
I traced a bug back to sth essentially like this:

Code:
$key = 0;
if ($key == "text") {
    echo "true";
} else {
    echo "false";
}

This evaluates to TRUE. I realize it may have to do with mixing types, but IMO it should still be FALSE. PHP thinks otherwise. Why?


Why is this true? - El Forum - 07-27-2010

[eluser]mddd[/eluser]
If a comparison involves a number, the other item is also converted to a number.
So php converts 'text' to a number and then compares the two.
'text' converted to a number equals 0 because it doesn't start with a digit.
So $key == 'text' becomes 0 == 0 and that's true.

Bottom line: if you want to compare something to a text, make sure it is not a number..
$key = ''; or $key = false; would probably both have worked like you expect.


Why is this true? - El Forum - 07-27-2010

[eluser]WanWizard[/eluser]
My guess:

You are comparing an integer with a string. PHP wants to do an integer compare. It therefore converts "text" to an integer, which is 0, and 0 == 0 evaluates to true.

Compare that with:
Code:
$key = 0;
if ((string) $key == "text") {
    echo "true";
} else {
    echo "false";
}



Why is this true? - El Forum - 07-27-2010

[eluser]John_Betong[/eluser]
This evaluates correctly:
Code:
<?php    
$key = 0;
if ($key === "text") {
    echo "true";
} else {
    echo "false";
}
echo '<br />',$key;
die;
?&gt;

&nbsp;
&nbsp;


Why is this true? - El Forum - 07-27-2010

[eluser]Steven Ross[/eluser]
Thanks!
Always learning...