I usually write this:
if ($myvar == null)
but sometimes I read this:
if (null == $myvar)
I remember somebody told me the latter is better but I don't remember why.
Do you know which is better and why?
Thanks, Dan
NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0 , "0" , "" , and false . Show activity on this post. Null is nothing, False is a bit, and 0 is (probably) 32 bits.
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.
== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.
PHP will compare alpha strings using the greater than and less than comparison operators based upon alphabetical order. In the first example, ai comes before i in alphabetical order so the test of > (greater than) is false - earlier in the order is considered 'less than' rather than 'greater than'.
If you accidentally forget one of the =
, the second one will give an error.
if ($myvar = null)
This will assign null
to $myvar
and perform the if
check on the result.
if (null = $myvar)
This will try to assign the value of $myvar
to null
and give an error because you cannot assign to null
.
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