Variable position in comparision in PHPAsk Question

问题:

Which is more optimized between 2 case below?

if ($var == 'value') {} 

and

if ('value' == $var) {}

Sorry if this is duplicated with another question but I can not google out the answer.

Thanks

[UPDATE]

This's called Yoda Conditions, more information here.

回答1:


There's no actual difference. The second one is used to defend yourself from typo if ($var = 'value') But not really readable. Use mostly the first one unless you are so tired that while typing you miss characters.

If you write code

if ($var = 'val') echo $var; //Output will be "val"

but if you do

if ('val' = $var) echo $var;

You'll get syntax error.

回答2:


'value' == $var is called a yoda condition. And generally is not used, because it is less readable.

In performance matter, I'm not sure, but I guess your interpreter generate the exact same opcode.

回答3:


The mostly used one is $var=="value" and if you want to it optimize then instead of == use ===

回答4:


I suggest to use

$var == 'value'

form to increase readability. I do not think there is a real performance gap between the two, php.net does not have any info on it (or i could not find it).

标签:
© 2014 TuiCode, Inc.