Variable before or after the value in the IF expression

Is there a difference between the two statements:

if ($a == 'hello') { ... }

and

if ('hello' == $a) { ... }

I noticed that applications like Wordpress tend to use the latter, while I usually use the former.

It seems that I remember something, I once read something, giving excuses for the latter, but I can not remember the argument.

+6
source share
2 answers

There is no difference. It is used so that an error occurs when the task is performed randomly instead of comparing:

 if('hello' = $a) 

if($a = 'hello') assigns to a variable and does not throw an error.

It can also be used to explicitly show that if you have an assignment in an if , you really want it to be there, and that is not an error (consistency).

+9
source

The essence of the justification for the latter is that if you mistakenly type = instead of == (instead of comparing), you will get a compiler error (you cannot assign a constant).

+2
source

Source: https://habr.com/ru/post/892397/


All Articles