1

I saw the following code which uses if ($page!==false). What are the differences if I use if ($page)?

if($id){ // check that page exists
$page=dbRow("SELECT * FROM pages WHERE id=$id");
if($page!==false){
    $page_vars=json_decode($page['vars'],true);
    $edit=true;
}

Thanks in advance.

shin
  • 31,901
  • 69
  • 184
  • 271
  • 1
    See also [What does this symbol mean in PHP](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php). It's an explicit value+type check here, for the logic redundant since an empty array and NULL should be treated equivalent. – mario Jan 16 '11 at 12:04
  • in your particular case there is no difference. – Your Common Sense Jan 16 '11 at 12:39
  • @Col. Shrapnel, how do you know what `dbRow` returns? It could plausibly be different if `dbRow` can return an empty array. – Matthew Flaschen Jan 16 '11 at 12:45

4 Answers4

4

With $page !== false, this only checks to see if $page is of boolean type (i.e. true or false) and if it is equal to false. if ($page) checks to see if the boolean representation of $page is false. The following values are false when converted to booleans in PHP:

  • null
  • 0 (integer)
  • 0.0 (float)
  • '' (empty string)
  • '0' (string containing the character 0)
  • array() (empty array)

So, if $page is any of these, if ($page) will fail, but if ($page !== false) will pass.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
2

The === and !== compares by value and type (strict comparison).

The == and != compares by value only (loose comparison).

In your case, the $page!==false only evaluates true when $page is not a boolean with the value false.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

If you use if($page!==false) you are making sure that $page is not false (in this case if $page is 0 or null will not be considered as false as you are forcing type check with !== )

If you use if ($page) it means any thing other than false, 0, NULL, empty string, empty array or any thing that computed as TRUE

shankhan
  • 6,343
  • 2
  • 19
  • 22
1

There are some falsy things that are !== false, such as NULL, 0, array(), and the empty string. The complete list of falsy values is here.

!== operates by checking that both type and value are identical. So $page !== false will be true unless $page is a boolean with the value false.

In contrast if($page) will result in the block being executed if $page is anything truthy (evaluating to TRUE). This is basically everything except the values listed in the above link.

Thus, the behavior is different for the falsy values that aren't exactly false.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539