if statement value position - php

What is the difference between the 2 statements:
if (false === $variable) {
//do something
}
and
if ($variable === false) {
//do something
}
I personally use the second style but often run into code in frameworks that i use which always seem to use the first style.
Is there a difference ( i suspect it is some legacy thing to do with types) or is this simply a coding habit (it must be rooted in something though??)
If not, what is the reasoning behind the first style given that the logic is actually backwards.

if ($foo = false) (note: = instead of ==) is a typical typo that leads to hard to debug problems. For that reason, some people prefer false == $foo, since the runtime will throw an error when you try to assign something to false.
Other than that there's no difference.

If you put the value that can't have something assigned to it (a literal, a constant, a function call, etc) on the left hand side then, if you accidentally use an assignment operator (=) instead of a comparison operator, then you'll get an error rather then a hard-to-track-down bug.
i.e.
if (false = $variable) { // Error
if ($variable = false) { // Valid code that doesn't do what you want

This dates to C programming. It's a way to make sure "compilers" will fail if you accidently used = (assignment) and not == or === (equals) because "false" is not an lvalue (can't be on the left side of an assignment)

It stems from this:
if (false = $variable)
syntax error
if ($variable = false)
accidental assignment

It has been around for a while. It comes from accidentally writing (by forgetting one =):
if (c = 1) {
}
which does assignment and it's doesn't actually check whether c equals 1. It assigns 1 and then it evaluates to 1 (so the if statement becomes always true due to that mistake). By writing
if (1 == c) {
}
as a habit, you cannot make that mistake. If you would forget the = in this case, the compiler would warn you because assignment to the literal 1 is not possible.

Practically, the two statements are equivalent.
So, why to write it this way or the other (?) :
Try to avoid a typical typo : if ($condition = false) instead of if ($condition == false). In that case, your 2nd version would cause a difficult-to-debug issue, while the first would throw an error
Want to force one of the two parts of the conditional statement be evaluated first (the rightmost)

Related

Comparison complexity from left to right [duplicate]

This is a question that is bugging me for a long time and can't find any answer...
Noticed it's used quite a lot by Zend Framework Developers,
What is the difference between following 2 "if" statements? :
if (null === $this->user) { ... }
if ($this->user === null) { ... }
To me the first one looks kinda odd ;]
Thanks for answer.
This is not a difference for the way your script works, it's just a coding standard, a recommendation
The reason why it is recommended to use it this way:
if (null == $this->user)
is the fact that if you mistype and write = instead of == you will get an error, while
($this->user = null)
instead of
($this->user == null)
works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)
and I guess it just extended as a habit to the strict comparison operator (===)
Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions, you can read more about it on this wikipedia page for example.
It is a good practice for writing if statement. Consider this code:
if (10 == $var) {
echo 'true';
} else {
echo 'false';
}
If you forgot one equal sign:
if (10 = $var) { }
Then PHP will generate parse error, so you know you missed one = and you can fix it. But this code:
if ($var = 10) { }
will assign 10 to $var and always evaluates to true condition. Whatever the contents of $var, the code above will always echo 'true' and its very difficult to find this bug.
These are called yoda conditions.
The idea is that if you put the value first (such as false, null, true or anything short) it becomes easier for a person to scan the statement and quickly understand the intention of the condition.
Also, what mishu said :)
There is no difference in order when comparing values.
It may be easier for someone to read or write such a code, but to me it's the same as writing from right to left.
Such order of elements in comparison I think is meant to prevent accidental assignment in if statements.
The result will be the same, however, the second is logical.
You want to check if the variable is NULL, not if NULL is the variable...
The reason for doing it the other way around is described here:
http://umumble.com/blogs/Programming/321/
If you accidentally write:
if (null = $this->user) { ... }
you will get a syntax error.
If you accidentally write:
if ($this->user = null) { ... }
you will be searching for a reason of strange behavior of your application for a long time.

Why do some people put the value before variable in if statement?

For example, what's different from $variable === true?
<?php
if (true === $variable) {
//
}
if (1 === intval($variable)) {
//
}
They are equivalent.
Some programmers prefer this "Yoda style" in order to avoid the risk of accidentally writing:
if ($variable = true) {
// ...
}
, which is equivalent to
$variable = true;
// ...
, when they meant to write
if ($variable === true) {
// ...
}
(whereas if (true = $variable) would generate an obvious error rather than a potentially-subtle bug).
Short answer
Some people do it in order to avoid mistakenly using the assignment operator (=) when they really meant to use a comparison operator (== or ===).
Long answer
In PHP there are 3 operators that can be mistaken for eachother:
= is the assignment operator
== is the "equal to" operator
=== is the "identical to" operator
The first operator is only used for assigning a value to a variable. The second and third are only used for comparing two values, or expressions, against eachother.
In PHP it is possible to assign a value to a variable inside control structures (if, for, while, etc.). This may cause problems if you are not careful. For example, if you want to compare $a against a boolean value you can do it like this:
if ($a == false) // or
if ($a === false)
If you are not careful, however, it may end up like this:
if ($a = false)
... which is perfectly legal code, but it is an assignment and will eventually cause problems. The reason it will cause problems is because the expression, $a=false, will be evaluated and the code will keep running as if nothing is wrong, when in fact it was not intended.
The reason some people switch around the operands, when comparing a value against a literal (fixed value, like true, false, 7, 5.2, and so on), is because it is not possible to assign a value to a literal. For example:
if (false = $a)
... will cause an error, telling the programmer that they made a mistake, which they can then fix.
I guess this is just the way of thinking in general. When you really think about a deep if statement, you think if that statement is true, not the other point of view. It's not wrong, but in my head naming it inverse, would annoy me and make me lose concentration about the statement. So I would say it's just the way people think :D.
There is no difference between ($var === true) and (true === $var). They are equivalent.
See http://php.net/manual/en/types.comparisons.php for a complete table of comparisons. You'll see that all equivalent comparisons have the same result.
Also, some people do prefer to see what's the result which is been evaluated before the statement.
Some statements might be longer and harder to read.
Ex:
if (false == (new DataParser()->makeAComplexDataParser((new SomeTransformer()->doTransformation((new someClass()->getMethodOfLongParameters($param1, $param2, (new Date()->format('Y-m-d')))))))) ) {
// do stuff
}
So it's better to think "is it false this complex expression?" instead of thinking
"this looooooooonger complex expression is....hmmmm....false?"

PHP - reversed order in if statement

This is a question that is bugging me for a long time and can't find any answer...
Noticed it's used quite a lot by Zend Framework Developers,
What is the difference between following 2 "if" statements? :
if (null === $this->user) { ... }
if ($this->user === null) { ... }
To me the first one looks kinda odd ;]
Thanks for answer.
This is not a difference for the way your script works, it's just a coding standard, a recommendation
The reason why it is recommended to use it this way:
if (null == $this->user)
is the fact that if you mistype and write = instead of == you will get an error, while
($this->user = null)
instead of
($this->user == null)
works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)
and I guess it just extended as a habit to the strict comparison operator (===)
Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions, you can read more about it on this wikipedia page for example.
It is a good practice for writing if statement. Consider this code:
if (10 == $var) {
echo 'true';
} else {
echo 'false';
}
If you forgot one equal sign:
if (10 = $var) { }
Then PHP will generate parse error, so you know you missed one = and you can fix it. But this code:
if ($var = 10) { }
will assign 10 to $var and always evaluates to true condition. Whatever the contents of $var, the code above will always echo 'true' and its very difficult to find this bug.
These are called yoda conditions.
The idea is that if you put the value first (such as false, null, true or anything short) it becomes easier for a person to scan the statement and quickly understand the intention of the condition.
Also, what mishu said :)
There is no difference in order when comparing values.
It may be easier for someone to read or write such a code, but to me it's the same as writing from right to left.
Such order of elements in comparison I think is meant to prevent accidental assignment in if statements.
The result will be the same, however, the second is logical.
You want to check if the variable is NULL, not if NULL is the variable...
The reason for doing it the other way around is described here:
http://umumble.com/blogs/Programming/321/
If you accidentally write:
if (null = $this->user) { ... }
you will get a syntax error.
If you accidentally write:
if ($this->user = null) { ... }
you will be searching for a reason of strange behavior of your application for a long time.

Why do some coding guidelines change the order of conditions in PHPs if/else?

Some coding guidelines state that you should put the variable you are testing at the end of the condition:
// Incorrect
if($isSomething === FALSE) { // Do something }
// Correct
if(FALSE === $isSomething) { // Do something }
I know that some programmers have the bad habit to initalize variables in conditions like that:
if($results = $db->getResults() { // Do something if results exist }
So the only reason I could imagine for having this counterintuitive rule is to prevent wrong reinitalisation in case you accidentally use just one equal sign (=) instead of two in PHP.
Are there any other reasons?
You can not accidentally assign a value in the case you wanted to compare.
This makes finding small errors much easier.
if (FALSE = $isSomething) will throw an error, as you can not reassign constants
wheras
if ($isSomething = FALSE) will always return true and you will probably not notice that error for a long time.

Variable before or after value in IF statement

Is there a difference between these two statements:
if ($a == 'hello') { ... }
and
if ('hello' == $a) { ... }
I've noticed applications like Wordpress tend to use the latter, whereas I usually use the former.
I seem to remember reading something a while ago giving justification for the latter, but I can't recall the reasoning behind it.
There is no difference. It is used so that an error is thrown in case you accidentally make an assignment instead of a comparison:
if('hello' = $a)
if($a = 'hello') would assign to the variable and not throw an error.
It might also be used to explicitly show that if you have an assignment in an if statement, you really want to have it there and it is not a mistake (consistency).
The justifikation for the latter is that if you mistakenly type = instead of == (assignment instead of comparision) you'll get compiler error (can't assign to constant).

Categories