I saw th开发者_开发百科e 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.
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 character0
)array()
(empty array)
So, if $page
is any of these, if ($page)
will fail, but if ($page !== false)
will pass.
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
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:
- Truth table in PHP
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
.
精彩评论