Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 919
steveneaston Avatar asked Jul 09 '11 15:07

steveneaston


People also ask

Can you put a variable in an if statement?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.

Can we assign a value to variable in if condition?

Yes, you can assign the value of variable inside if.

What goes after an if statement?

The IF statement evaluates the given conditional expression. If the result is true (i.e. nonzero), then the statements following the <IF> tag are executed. If the result is false, those statements are skipped and control falls to the next statement after the closing </IF> tag.

Why do we use & before variable?

The & means "Don't take the variable, take the place in memory where this variable is stored." It's a little complicated, but it's necessary so that C can change the value of the variable.


2 Answers

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

like image 95
Felix Kling Avatar answered Sep 28 '22 04:09

Felix Kling


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

like image 22
ain Avatar answered Sep 28 '22 04:09

ain