What is the difference between these php expressions?

What is the difference between these php expressions ??

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

Some frameworks, such as the Zend Framework, use the latter form, while the traditional form uses the former.

Thanks in advance

+7
php expression if-statement
source share
6 answers

the result of the expression is the same, but this is a good way to protect yourself from being assigned instead of comparing (for example, writing if ($ var = false) instead of if ($ var = false), since you cannot assign the value $ var to the keyword "false ")

+10
source share

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

 if ($var == false) 

because if you accidentally print it with the letter = 1, the condition will always be true (because $ var will be set successfully), but in case

 if (false == $var) 

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

+2
source share

The two expressions are semantically identical. It is simply a question of whether to put the constant expression first or last.

+1
source share

There is no real difference. Operands only from different angles, but a comparison nonetheless.

0
source share

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

0
source share

Consider this scenario:

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

If $substring is at the exact start of $string , the return value is 0. Unfortunately, inside the if, this evaluates to false , so the condition is not met.

The correct processing method:

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

Output:

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

0
source share

All Articles