In php 5
$my_var = "";
if ($my_var == 0) {
echo "my_var equals 0";
}
Why it evaluates true? Is there some reference in php.net about it?
PHP is a weakly typed language. Empty strings and boolean false will evaluate to 0 when tested with the equal operator ==
. On the other hand, you can force it to check the type by using the identical operator ===
as such:
$my_var = "";
if ($my_var === 0) {
echo "my_var equals 0";
} else {
echo "my_var does not equal 0";
}
This should give you a ton of information on the subject: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
A string and an integer are not directly comparable with ==
. So PHP performs type juggling to see if there is another sensible comparison available.
When a string is compared with an integer, the string first gets converted to an integer. You can find the details of the conversion here. Basically, since ""
is not a valid number, the result of the conversion is 0
. Thus, the comparison becomes 0 == 0
which is clearly true.
You'll probably want to use the identity comparison ===
for most (if not all) your comparisons.
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