2

I was reading a piece of code and saw that the author of the code uses the following if statement

if ( 'string' == $var )

where as I always use

if ( $var == 'string' )

What i'm wondering is if this has any other function except for style/looks. Is comparing a $var to a 'string' quicker/slower than a 'string' to a $var?

8
  • stackoverflow.com/questions/29910258/… Commented May 4, 2015 at 11:23
  • 1
    It's called yoda condition! Commented May 4, 2015 at 11:23
  • $var ='string' ; if ( 'string' == $var ){ echo "HI"; } No differenece echoes HI Commented May 4, 2015 at 11:23
  • 1
    The difference is if you make a typo and use = instead of == Commented May 4, 2015 at 11:24
  • Also see: stackoverflow.com/a/28840422/3933332 Commented May 4, 2015 at 11:25

1 Answer 1

2

Why if( constant == variable ) is preferred instead of if ( variable == constant )

Here is an answer to your question. This helps in debugging if you miss an equal sign.

Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:

if (k = 5) This was intended as a comparison, but it's now an assignment! What's worse, it is legal, and it will mess up your program in multiple ways (the value of k is changed, and the conditional always evaluates to true).

Contrast this with

if (5 = k) This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.

in the words of Hanky 웃 Panky in comments:

They are both equivalent but 'string'==$var is a better approach because it helps in debugging if you miss an equal sign.

Sign up to request clarification or add additional context in comments.

3 Comments

This is a comment not an answer!
It would have been a very nice answer had you improved your statement to make it complete. Something like They are both equivalent but 'string'==$var is a better approach because it helps in debugging if you miss an equal sign.
Even though it's not an answer to my question it is in fact what I secretly was looking for without realizing it myself. I've always been using the k = 5 notation but do realize now that apparently it's bad practice or well the latter is preferred. I'll see if I can get myself to switching over to 5 = k :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.