DEV Community

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

Posted on

1

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 ! 💚

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay