Home > front end >  Why do so many examples in php reverse the sequence of arguments to comparison operators, e.g. 0 ===
Why do so many examples in php reverse the sequence of arguments to comparison operators, e.g. 0 ===

Time:10-18

In so many php examples I see e.g. if (0 === $i) { } instead of if ($i === 0) { }

I wonder where this comes from? All classical literature on algorithms and programming has it the way you would read it, with the variable first and the value second. So I wonder whether there is any computational benefit to it, and where this idea came from in the first place.

CodePudding user response:

This is called Yoda style and is popular among some PHP environments, like WordPress for example. It's considered a bad practice by many, including me.

The reason to use it is to avoid the single equal sign mistake:

if ($a = 5) {/* always true*/}

// vs.

if (5 = $a) {/* syntax error */}

CodePudding user response:

it's called the yoda condition, in case you accidently typed single = instead of 2 or 3 (example: 0 = $i) it will generate an error instead of variable assignement ($i = 0) which will make you lose some time debugging to find the problem

  • Related