Yoda condition, in PHP, What is ?

WBOY
Release: 2024-08-29 06:33:32
Original
936 people have browsed it

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
}
Copy after login

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
}
Copy after login

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

The above is the detailed content of Yoda condition, in PHP, What is ?. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!