Welcome Guest, Not a member yet? Register   Sign In
Why is this true?
#1

[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?
#2

[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.
#3

[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";
}
#4

[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;
#5

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




Theme © iAndrew 2016 - Forum software by © MyBB