Today I was playing with PHP, and I discovered that the string values "true" and "false" are not correctly parsed to boolean in a condition, for example considering the following function:
function isBoolean($value) {
if ($value) {
return true;
} else {
return false;
}
}
If I execute:
isBoolean("true") // Returns true
isBoolean("") // Returns false
isBoolean("false") // Returns true, instead of false
isBoolean("asd") // Returns true, instead of false
It only seems to work with "1" and "0" values:
isBoolean("1") // Returns true
isBoolean("0") // Returns false
Is there a native function in PHP to parse "true" and "false" strings into boolean?
Easiest Way to safely convert to a boolean;
I recently needed a "loose" boolean conversion function to handle strings like the ones you're asking about (among other things). I found a few different approaches and came up with a big set of test data to run through them. Nothing quite fit my needs so I wrote my own:
Note that for objects which are both countable and string-castable, this will favor the count over the string value to determine truthiness. That is, if
$object instanceof Countable
this will return(boolean) count($object)
regardless of the value of(string) $object
.You can see the behavior for the test data I used as well as the results for several other functions here. It's kind of hard to skim the results from that little iframe, so you can view the script output in a full page, instead (that URL is undocumented so this might not work forever). In case those links die some day, I put the code up on pastebin as well.
The line between what "ought to be true" and what oughtn't is pretty arbitrary; the data I used is categorized based on my needs and aesthetic preferences, yours may differ.
There is a native PHP method of doing this which uses PHP's filter_var method:
According to PHP's manual:
I'm using this construct to morph strings into booleans, since you want
true
for most other values:In PHP only
"0"
or the empty string coerce to false; every other non-empty string coerces to true. From the manual:You need to write your own function to handle the strings
"true"
vs"false"
. Here, I assume everything else defaults to false:On a side note that could easily be condensed to
No - both are strings, and those both (as you say) evaluate to
true
. Only empty strings evaluate tofalse
in PHP.You would need to test for this manually. If at all possible, though, it would be better to work with "real" boolean values instead.