I have this code:
$test = 0;
if ($test == "on"){
echo "TRUE";
}
Result of this code will be:
TRUE
WHY??? My version of PHP: 5.4.10.
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
$test = 0;
if ($test === "on"){
echo "TRUE";
}
PHP will convert the string to number to compare. Using ===
, will compare the value as well as the type of data.
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
Docs
Because you are comparing $test
with string value not binary value, if you want to compare with string value, try with ===
comparison, for
value + dataType
.
In your example, var_dump(0=="on");
always return bool(true)
.
But when you use var_dump(0==="on");
it will give you bool(false)
.
Example from PHP Manual:
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With