What's the difference between those PHP if expressions?
Asked Answered
C

6

7

What's the difference between those PHP if expressions!?

if ($var !== false)
{
    // Do something!
}


if (false !== $var)
{
    // Do something!
}

Some frameworks like Zend Framework uses the latest form while the traditional is the first.

Thanks in advance

Cassella answered 21/4, 2010 at 13:31 Comment(0)
M
10

The result of the expression is the same however it's a good way of protecting yourself from assigning instead of comparing (e.g writing if ($var = false) instead of if ($var == false), since you can't assign the value $var to the false keyword)

Macrobiotic answered 21/4, 2010 at 13:36 Comment(0)
D
2

It's just a preference really. You can put it either way, a == b or b == a, but it's easier to make a mistake if you do

if ($var == false)

because if you accidentally type it with one = letter, the condition will always equal to true (because $var will be set successfully), but in case of

if (false == $var)

if you now put in =, you will get an error.

Domingo answered 21/4, 2010 at 13:44 Comment(1)
Nitpick: "because if you accidentally type it with one = letter, the condition will always equal to true" - this is not true. if ($var = false) is the same as $var = false; if ($var). Ergo, it will always evaluate to false.Mario
I
1

The two expressions are semantically identical. It's just a matter of preference whether to put the constant expression first or last.

Incessant answered 21/4, 2010 at 13:36 Comment(0)
W
0

There's no real difference. The operands are just on different sides but the comparison is the same nonetheless.

Westleigh answered 21/4, 2010 at 13:36 Comment(0)
E
0

There is no difference. !== compares 2 expressions with type checking, and returns true if they are not equal. The difference may be in the evaluation order of the expressions, but in the case you wrote, there is no difference (and a good program must not rely on the execution order of such expressions).

Elissa answered 21/4, 2010 at 13:37 Comment(0)
D
0

Consider this scenario:

if (strpos($string, $substring)) { /* found it! */ } 

If $substring is found at the exact start of $string, the value returned is 0. Unfortunately, inside the if, this evaluates to false, so the conditional is not executed.

The correct way to handle that will be:

if (false !== strpos($string, $substring)) { /* found it! */ }

Conclusion:

false is always guaranteed to be false. Other values may not guarantee this. For example, in PHP 3, empty('0') was true, but it changed to false later on.

Deathless answered 21/4, 2010 at 13:41 Comment(1)
I didn't downvote you, but you didn't answer the question. The OP isn't asking the difference between if ($var) / if (func()) and if ($expectedValue === $var) / if ($expectedValue === func()), but just why it would be a better idea to list constants before variables in if-statement conditionals.Mario

© 2022 - 2024 — McMap. All rights reserved.