DEV Community

Cover image for Yoda condition, in PHP, What is ?
thiCha
thiCha

Posted on

Yoda condition, in PHP, What is ?

While scrolling through code you might come across something like this if (1 === $var).

What could possibly be the difference between if ($var === 1) and if (1 === $var) ?

if ($var === 1)

  • This is how we learn the code because it you can write the same way you speak: if the variable $var is equal to 1 then do something.

if (1 === $var)

  • This is known as the โ€œYoda conditionโ€ from the famous Jedi Master speaking backwards.

It has to be known that there is no difference in functionality between the two approaches. So, why the hell would you use a Yoda condition when writing conditions ?

The only reason why the Yoda condition is used

When writing an if statement, it may have happened that you missed some equal signs. The problem is when you end up with something like this:

if ($var = 1) { // Instead of $var === 1
    // Do something
}
Enter fullscreen mode Exit fullscreen mode

What happens here ?

No error is detected because this is code is valid. The problem is that it does not work like intended: the variable is assigned to the value 1, no comparison is performed and it is always true.

This is where the Yoda condition is useful; with the same case, we get:

if (1 = $var) { // Instead of 1 === $var
    // Do something
}
Enter fullscreen mode Exit fullscreen mode

Here we also missed some equals but the code is not valid and, this time, we get an error since this is not valid.

Conclusion

We have seen that the sole purpose of the Yoda condition is to avoid accidental assignment which comes at the cost of less readeability.

Should you use it ? Why not ! But keep in mind that this will not improve your code by any margin.

Also it can help to flex at a party with devs (which does not occur that often by the way).

For you reading, thank you ! ๐Ÿ’š

Top comments (0)