views:

111

answers:

6

Hello,

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

A: 

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

John Conde
+9  A: 

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)

matei
+1  A: 

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

klausbyskov
A: 

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).

petersohn
A: 

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.

Sarfraz
why down vote?????
Sarfraz
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.
pinkgothic
+3  A: 

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.

Kai Sellgren
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.
pinkgothic