boolean in if statement
If I want to execute code only if a variable开发者_运维技巧 is true
, should I have:
if ($option) { /* code */ }
or
if ($option == TRUE) { /* code */ }
Doesn't the first one imply that also values like 1, 2, 3 etc. will execute the code.
Is the second one the better option?
I think what you are looking for is the ===
operator. The manual gives a decent description of the various comparison operators.
The ===
operator compares type as well as value.
You may also be interested in the PHP Caparison Tables. They will describe how the comparison operators work when comparing two different types.
Both those statements are essentially the same since, as you pointed out, PHP evaluates several values as true
.
If you want your comparison to match strictly boolean TRUE variables, your second statement should use:
$option === TRUE
Basically what php does its to transform to the most simple type. in this case it will convert the integer to boolean, any integer greater tan 0 will be true, so if $option has an integer greater tan zero its equivalent to a true boolean value.
check out this table to understand it better.
http://www.php.net/manual/en/types.comparisons.php
精彩评论