Rooxie Rooxie - 1 year ago 68
PHP Question

Comparison order in PHP IF

I'm pretty sure that there is no difference between this

if ($value === true)

and this

if (true === $value)

For me it always seems confusing. I used to think that it's a 'bad unconventional style of new developers'. Furthermore, my boss told me never to do such a thing.

But today I was looking through Slim's source code, written by the guy who created PHP: The Right Way, and saw this (line 341).

if (true === $value) {
$c['settings'] = array_merge_recursive($c['settings'], $name);

I'm sure a guy like Josh Lockhart wouldn't do something like this if it was considered a bad practice. So what's with this order? Is it some kind of an old tradition?

Answer Source

This is colloquially referred to as 'Yoda Conditions'. The reasoning behind their usage is because sometimes people make mistakes. In the context of an if statement, this is one such mistake that is sometimes made:

if($value = 42)

Notice there is no double equals sign (==). This is a valid statement and is not a syntax error. It is possible that it would cause huge disruptions with the code that follows it, and is very hard to identify. Yoda conditions get around this by reversing the conditional expression:

if(42 = $value)

Now this is not a valid statement and is a syntax error, and those are generally reported with a line number included, so they're pretty easy to find.

Whether or not you actually think they're good or bad is up to personal preference and style. In some cases of popular frameworks (such as Wordpress), Yoda conditions are actually part of the official coding standards. The major critique against them is that, to some, they decrease readability of the code without providing any real major benefit.

"Syntax error you have. Do something else you must." -- Yoda, probably

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download