Which is good to use and why?
if ($a == 3) {
//do something
}
Or
if (3 == $a) {
//do something
}
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.
Sign up to join this communityWhich is good to use and why?
if ($a == 3) {
//do something
}
Or
if (3 == $a) {
//do something
}
Neither and both.
The 'both'
x == $assignedVariable
is a method of defensive programming which is aimed at preventing accidental assignment if someone was to use $x = 3
by mistake. Whether this offers value is debatable; modern systems exist which catch these mistakes, IDE' can flag this easily and its a bit moot given that someone can accidentally do $x = 3
just as easily as 3 = $x
. The difference is assignment vs exception.
The 'neither'
You are using a truthy condition(==) which in your example should be changed to a value and type check(===). Truthy checks absolutely still do have a place but within the confines of your example a type check is definitely suitable. Take the following example which should highlight the point.
var_dump($a == 3); // true
var_dump($a === 3); // true
var_dump($a == "3"); // true
var_dump($a === "3"); // false