6

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.

steveneaston
  • 259
  • 1
  • 4
  • 10

2 Answers2

9

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    This pretty much sums it up, though I'd just like to mention that while using this style may prevent errors, it does make the if-clauses harder to read sometimes. – Jani Hartikainen Jul 09 '11 at 15:42
  • Thank you for the explanation. By the way, I hate that "unnatural" style. – Nick Jul 13 '11 at 12:07
2

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

ain
  • 22,394
  • 3
  • 54
  • 74