开发者

What's the difference between those PHP if expressions?

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

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


if (false !== $var)
{
    // Do someth开发者_StackOverflow中文版ing!
}

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

Thanks in advance


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)


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.


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜