In PHP,
null==0
0=="0"
If you combine these two, you would expect:
null=="0"
But this is not true.
Could someone explain this to me?
In PHP,
null==0
0=="0"
If you combine these two, you would expect:
null=="0"
But this is not true.
Could someone explain this to me?
In the first case:
null==0
null
evaluates to false
, same as 0
which evaluates to false
, so both are false
and so the comparison returns true
.
In second case:
0=="0"
here you are comparing two variables of different type, one is numerical and other string, because you are not using the === operator, PHP cast one of them to the other type so 0 casted to string equals "0" which so they are the same, if it's "0" which is casted to number also casts to 0 so its the same as the other value, and so this comparison returns true.
In third case:
null=="0"
here's the same situation, both are different types so PHP cast one of them to the type of the other, but if you cast null to string the result is "null" which is not equal to "0", so that's the reason is not true that comparison.
==
checks equality
===
checks equality AND type (we also say it is "identical")
Therefore, since PHP does not have strong type hinting, it is automatically casted to the best suited type.
null === 0
is false
while null == 0
is true because 0
or '0'
are considered as null value as well as false
. An empty value null == ''
will return true
too.
That's how PHP works.
A best practice is to always check for type using the ===
operator (and its negative equivalent, !==
and use only the other in special cases).
You have to understand that because PHP is not strict in its typing it is often casting your variables to other types depending on the comparison or operation needed. In the case of null==0 it is telling you that both null and integer 0 are considered false.
In the case of null == "0" it is checking if the string "0" is empty which it is not. Comparing integer 0 with string "0" type cases "0" to an int for comparison in which case they are equal.
Hope that helps.