Question about the conditions

Hello, I wonder about the conditions after watching many PHP codes.

I find such conditions as follows:


<?php
if($number === 42) {
 echo 'Yes, this number is 42';
} else {
  echo 'Oh, this number is ' . $number;
}
?>

and


<?php
if(42 === $number) {
 echo 'Yes, this number is 42';
} else {
  echo 'Oh, this number is ' . $number;
}
?>

Personally I’m used to the first condition that seems more logical.

But can you tell me more?

Thank you

Basically, the first one is easier to understand, but prone to potential bugs.

The second is harder to understand, but there is no potential bug.

The bug comes from forgetting the second =, so

if ($number = 42) and forgot the second =, it will always be true as well as corrupt the value of $number, so this runtime error might not be identified.

however if you reverse the order, it will throw an error so this bug is spotted right away.

The second instance is called a yoda condition (after Yoda from starwars, who very strangely talk he does) since it’s (arguably) the “wrong way around”, i.e., “if 42, the value is”

The advantage of yoda conditions is that you can’t accidentally assign when you wanted to compare; for example


if ($something = 42) {
   // etc
}

This will just assign 42 to $something and then execute the body, whereas


if (42 = $something) { 
  // etc
}

will raise an error (Parse error: syntax error, unexpected '=') because you can’t assign a new value to 42 (for obvious reasons, lol).

Does that help or just trouble the waters more? :slight_smile:

Edit:

^ what he said :slight_smile:

Thank you, and do you know if terms of performance there is a code that is meillur than the other?

In theory the two methods should be equally fast, but I’m not sure on the PHP internals on this one.
Maybe @Salathe; can help us out in that regard?

There is no performance reason to pick one way over the other.

Some folks prefer the literal == $variable ordering but that is only because it makes catching the one-too-few-equals-characters mistake easier to catch, as explained above. (: