如何对待布尔值?
I've received a boolean from a query, and I want to check if the boolean's value is greater than zero. Is it possible to modify the approach used when handling resources to check a boolean's value? (See; example of resource handling below:)
return (mysql_result($query, 0) == 1) ? true : false;
Any help appreciated. Thank you in advance.
Since PHP would interpret as a string, you can simply cast it as (bool)
return (bool)(mysql_result($query, 0));
Non-zero values will cast as TRUE
. Note that you should only do this if the return values are 0 or 1. Negative values will cast as TRUE
.
var_dump((bool)"1");
// bool(true)
var_dump((bool)"0");
// bool(false)
var_dump((bool)-2);
// bool(true)
Just do return mysql_result($query, 0) == 1;
Don't do something like return $a_boolean_value ? true : false;
.
I've received a boolean from a query
that is not true. you can't get boolean from the query but merely a string.
I want to check if the boolean's value is greater than zero.
booleans cannot be measured in that way. boolean can be either true or false. or, it you like it - zero or non-zero. not "greater" but just "not".
'greater than' operator in PHP is
>
. so, you can use it in your expression instead ofequal
operator(==
one)