lezhni
lezhni

Reputation: 304

Php: if or else

Imagine, that you have a variable called $varName. It can take one of two values: 'aaa' or 'bbb'. So, which statement will be optimal and why?

1)

if ($varName === 'aaa') {
/* Code for 'aaa' */
} else {
/* Code for 'bbb' */
}

2)

if ($varName === 'bbb') {
/* Code for 'bbb' */
} else {
/* Code for 'aaa' */
}

3)

if ($varName == 'aaa') {
/* Code for 'aaa' */
} else {
/* Code for 'bbb' */
}

4)

if ($varName == 'bbb') {
/* Code for 'bbb' */
} else {
/* Code for 'aaa' */
}

UPD: Variable take 'aaa' value more ofter than 'bbb'

Upvotes: 0

Views: 161

Answers (1)

Filip Juncu
Filip Juncu

Reputation: 362

If you know for sure $varName gets the (string) "aaa" more often then option (1) would be optimal for two reasons:

  1. Operator "===" does not convert the data. See this answer for more details.
  2. The code will proceed to the else part less often.

PS. The performance differences are insignificant, it is much more about readability.

Upvotes: 1

Related Questions