Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable position in comparision in PHP

Tags:

php

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.

like image 898
thang nhoc Avatar asked Dec 01 '25 15:12

thang nhoc


1 Answers

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.

like image 90
Leri Avatar answered Dec 03 '25 10:12

Leri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!