Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: order of operators in a comparison null

Tags:

operators

php

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

like image 218
Tom Avatar asked Oct 25 '10 13:10

Tom


People also ask

IS NULL == false in PHP?

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.

What is precedence of operators in PHP?

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.

Why would you use === instead of == in PHP?

== 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.

How does PHP compare strings with comparison operators?

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'.


1 Answers

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.

like image 159
SLaks Avatar answered Nov 16 '22 02:11

SLaks