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?
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.
In your first line, you define $my_var
as string.
Inside the comparison you compare that variable with a constant integer.
If you want exact comparison (I don't know why you need to compare a string with an integer without any cast), you should use the ===
:
if ($my_var === 0) {
echo "my_var equals 0";
}
That will never echo the message.
The PHP manual defines in Comparison Operators section, the operator ==
as:
TRUE if $a is equal to $b after type juggling.
So, the important thing here is type juggling
.
As a matter of fact, in PHP Manual: types comparisons, the second table tell you exactly that integer 0
equals string ""
.
This is due to the type coercion that comes from the equality operator you are using.
The PHP manual has the Type Comparison tables to shed a light on this.
Its generally considered a good practice to utilize the identical operator ===
instead, as to avoid such corner(?) cases.
here is the reference in the php manual about boolean values
http://www.php.net/manual/en/language.types.boolean.php
and here is the reference for the NULL value
http://www.php.net/manual/en/language.types.null.php
$my_var = '';
if ($my_var == 0) {
echo "my_var equals 0"
}
evaluates to true because "" is the same as NULL which evaluates to false or 0