In php, ($myvariable==0)
When $myvariable is zero, the value of the expression is true; when $myvariable is null, the value of this expression is also true. How can I exclude the second case? I mean I want the expression to be true only when $myvariable is zero. Of course I can write
($myvariable!=null && $myvariable==0 )
but is there other elegant way to do this?
Identical TRUE if $a is equal to $b, and they are of the same type
Use the php function is_null( ) function along with the
===
operator.!==
also works the way you'd expect.The second solution wouldn't work either. The
===
operator is the solution to your problem.To identify as null or zero by:
is_int($var)
if a variable is a number or a numeric string. To identify Zero, useis_numeric($var)
is also the solution or use$var === 0
is_null($var)
if a variable is NULLYou hint at a deep question: when should an expression be true?
Below, I will explain why what you are doing isn't working and how to fix it.
In many languages
null
,0
, and the empty string (""
) all evaluate to false, this can makeif
statements quite succinct and intuitive, butnull
,0
, and""
are also all of different types. How should they be compared?This page tells us that if we have two variables being compared, then the variables are converted as follows (exiting the table at the first match)
So you are comparing a null versus a number. Therefore, both the null and the number are converted to boolean. This page tells us that in such a conversion both
null
and0
are consideredFALSE
.Your expression now reads,
false==false
, which, of course, is true.But not what you want.
This page provides a list of PHP's comparison operators.
The first comparator is the comparison you are using now. Note that it performs the conversions I mentioned earlier.
Using the second comparator will fix your problem. Since a null and a number are not of the same type, the
===
comparison will return false, rather than performing type conversion as the==
operator would.Hope this helps.
For my case i found this soulution and it works for me :