While using an 'if' statement to check whether a variable is an empty string or not we can write it in two ways i.e. if('' == $variable) and if($variable == ''). I want to know what is the impact of above in different cases?
Thanks in advance!!
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
In a modern language, you should be writing your conditions of the form
if($variable == ""). This makes the condition easier to read for natural English speakers.
In a legacy language, it sometimes was considered good practice to use the form
if("" == $variable) as if you used the more natural form it was possible to create compilable and runnable code which was bugged if you accidentally missed one of the '=' symbols.
Now, most compilers, even for these older languages, will at least warn you if you accidentally miss the '=' symbol.
TL;DR; - use
if($variable == "")
This highly depends on the language used!
== is implemented as a method in an object oriented language then the construct
if ($variable == "") could lead to an exception because the object (
$variable) might not be initialized or even
If you reverse the expression (
if ("" == $variable)) then you can be sure that the object acted on (
"" is always initialized and never
As an example in Java (where the method is called
can cause a
NullPointerException because the object
string may be
cannot lead to a
NullPointerException as the object
"" is never
== is not a method of an object then it does not matter which order is used.
I think that many programmers with such a background use the expression
if ("" == $variable) because they are more familiar with it.