Comparison complexity from left to right [duplicate] - php

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.

Related

Why use an extra set of parenthesis when using PHP boolean test in an IF()?

I'm sorry the title of this question is odd. I couldn't find a good way to word it!
The idea is simple, sometimes you see PHP tests this way:
if (!a_function("something")) { }
Here you can think of it as "if not true". I sometimes see the exact same thing but with extra parenz:
if (!(a_function("something"))) { }
Why does it require the extra parenz after the bang? Don't they both essentially mean if (!true)?
For extra bonus, what are the reasons for the two styles (does this have a name?) and maybe give examples of how they would give alternate results if not used correctly.
update:
Here is an example in a PHP script I'm using, the author is testing environment variables and seems to use the styles interchangeably:
if (!(extension_loaded("iconv"))) { ... }
if (!(extension_loaded("xml"))) { ... }
if (!function_exists("json_encode")) { ... }
if (!ini_get("short_open_tag")) { ... }
I know you can't answer for the programmer here, but why would they be alternating the use of extra parenz when these small functions are right next to each other?
I happen to know that, for example, the return value of ini_get is just the number 1, and the return value of the extension_loaded functions may also just be the number 1, so it seems like there would be no difference. I'm not 100% sure there isn't some other trick to this than simple preference or order of operation.
update 2:
I understand parenz can be used for either clarity, or order of operations, but I'm not convinced it is only personal preference beyond that.
In my example above, everything depends on what is returned by the functions that are being tested.
It's my understanding that by wrapping a statement in parenz, PHP will force it into a bool. But when it's not in parenz, could there be a return value that breaks the code without using the parenz around it to force a bool?
If people say, in my example code above, that there is nothing but personal preference going on, then I'll just have to accept that, but I have my doubts.
the parenthesizes are used in case if there are more than 1 logical operator with different precedence, to indicate that "!" operator must be applied after all other operators have been processed. For example:
if(!($var1 < $var2))
First will be checked if $var1 is less than $var2, and after that will be checked if the result is false.
If use that:
if(!$var1 < $var2)
then firstly will be checked if $var1 is false and the result will be compared to $var2, that simply do not make sense.
It's not required. It's a matter of personal preference. Sometimes you like to have extra parens to be EXTRA certain of how the expression will be evaluated.
if(a or b and c)
is confusing.
if ((a or b) and c)
is much more clear.
if(a or (b and c))
is much more clear.
They both work, but some people might have different opinions on which one is more readable.
Parenthesis are not required in the given case, but they can be if, for example, you also assign a variable at the same time :
if (($myVar = myFunc()) !== false) {
// Doing something with $myVar, ONLY if $var is not false
}
While, in the following case, it will change the logic
if ($myVar = myFunc() !== false) {
// Here $myVar = true or false instead of the wanted value
}
if( !(should_return_trueA() && should_return_trueB())) {
// at least one have returned false
}
esentially is the same as:
if( !should_return_trueA() || !should_return_trueB() ) {
// at least one have returned false
}
It's, in my case, a practice to avoid mistaken/ommited exclamation marks. Useful, when building more complex conditions and looking for all-false or all-true result.

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.

What's the meaning of the reverse entry (null === $value) when checking the value of the variable? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - reversed order in if statement
Checking for null - what order?
Examining Zend Framework found that they do all the variable checkings reverse way:
public function setBootstrap($path, $class = null) {
if (null === $class) { // instead of if($class === null)
$class = 'Bootstrap';
}
What's the reason of doing this?
Is this also suitable for Java and C++ programming?
some people believe it helps them in avoiding to write a single = (an assignment instead of a comparison for equality)
I believe that the advantage of doing so is much less than the loss of readability (and therefore maintainability!)
People who don't test their code may rely on this sort of trick. And to answer your question, yes, it is suitable for most languages who derive their syntax from C - I mean suitable, not recommended.
This style is called yoda conditions.
Basically it has the same behavior as the usual ( $variable === value ) style, but with one advantage:
The compiler throws an error in case you write = instead of == or === by mistake.
As you can't reassign a constant (in the example the null value), the developer immediately recognizes the mistake due to a compiler error/warning and thus is relieved of a time consuming bug search.
So the following line would be valid, although it wont show the (most of the time) intended behavior:
if ( $var = null ) { echo 'test'; }
While here an error is shown:
if ( null = $var ) { echo 'test'; }
A major drawback, however, is the loss of readability with this style. But this depends on the reader of the code and some other coding style guidelines.
This is a yoda condition, I dont know about any benefits except you cant assign the value to the variable when you accidentally write for example
if( $foo = "bar" )
Here a Link for more examples:
http://united-coders.com/christian-harms/what-are-yoda-conditions
In this case comparison takes in account value and a type of the value. this is a strict comparison.
For example this code:
if (null == "") {
echo "null";
}
Will print "null" as far as PHP treats "", 0, null, false as equivalent empty values unless strict comparison is used to compare actual value and type of the value itself.
Second thing is why null === $class is used is because you can not assign value to null. Whereas you can successfully make mistake and assign $class = null.

if statement value position

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)

Difference between variable === value and value === variable?

a)
if(null === $object)
{
//take some action
}
b)
if($object === null)
{
//take some action
}
I am in habit of doing like b) but in Zend-Framework I find everywhere they have done it like a) . Is there any benefits of it ??
Thanks.
No, there is no difference.
The latter is supposed to help to avoid silly typos when you write $a = null instead of $a == null (or $a === null). In first case you'll get logical error, because of assignment instead of comparison, in second case - you'll get fatal error which will help you to find an issue sooner.
There is no difference, it is used to avoid mistakes (like setting variable to null, not comparing them), however the null === $object is often considered the Bad Way (c) to avoid typos.
The $object === null expression is much more human-friendly then null === $object 'cause second one breaks nature reading order which is left-to-right. That's why even if there is no much difference for interpreter but it's a bit harder to read by a human. Involving some logic - if you use if..else statement how it should sounds like? "If null equals $object.. Wait a minute, null is null, how can it be equal to something else? Oh, Gee, we actually comparing right-handed value to left-handed one, it's reversed stuff. So, if $object equals null then we should..". And your think this way every time.
My conclusion is: use $value == const every time you can! Long time ago people wrote if ($value = const) but these times have passed. Now every IDE can tell ya about such simple errors.
b) is way more readable than a)
And a) is considered by some overcautious people as less error prone because of possible confusing == with =.
But in case of three ='s I doubt anyone will confuse it with one.
This a choice by the developer to attempt to stop accidential assignment of values.
The functionality is exactly the same between the two methods of comparison but in the case of "a" it stops any accidential assignment of values as you cannot assign something to null.
The second method checks the value and type of variable against null, The errors should be different in tow methods.

Categories