Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Condition Format - (6 == $var) or ($var == 6)?

I was browsing these PHP Coding Guidelines (a bit outdated but very interesting), and found this:

Condition Format

Always put the constant on the left hand side of an equality/inequality comparison. For example: if ( 6 == $errorNum ) ...

One reason is that if you leave out one of the = signs, the parser will find the error for you. A second reason is that it puts the value you are looking for right up front where you can find it instead of buried at the end of your expression. It takes a little time to get used to this format, but then it really gets useful.

I have been using ($var == 6) for years now and the idea of putting them the other way around is horrifying. But as mentioned, this takes a bit time to get used to and is supposed to have clear benefits. We are just writing up standard at our company so if we want to change this, this is the moment to do that. But I'd like to hear if other have experience with this particular format. Any opinions?

EDIT

I am interested in people's experience with making this switch. To me, and most likely to others, this looks like a big change that you need to get used to. But it looks interesting. So the question to those who have switched: can you recommend this change?

like image 765
user852091 Avatar asked Jul 21 '11 03:07

user852091


People also ask

What does == mean in PHP?

Equal Operator == The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two inputs to compare and returns true value if both of the values are same (It compares only value of variable, not data types) and return a false value if both of the values are not same.

What does == and === mean 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. Syntax: operand1 == operand2. === 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 do you pass two conditions in an if statement in PHP?

yes, you could use && and || for that. && is for 'and', || is for 'or'.


1 Answers

6 == $var has a real advantage that $var == 6 does not. There is nothing horrifying about it at all, it just looks different. You should get used to it and use it. In fact, I haven't gotten used to it yet and I forget about it frequently. You really have to think about it and use it since the opposite is so common.

The advantage, in case you didn't know, is to prevent simple syntactical mistakes, thus:

if ($var = 6) {} //weird semantic error
if (6 = $var) {} //parse error
like image 79
Explosion Pills Avatar answered Sep 30 '22 13:09

Explosion Pills