Test if string could be boolean PHP
If you use the flag FILTER_NULL_ON_FAILURE
, filter_var()
will work nicely:
function CheckBool($Value) {
return null !== filter_var($Value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
There's, by the way, a cleaner way of writing it:
function checkBool($string){
$string = strtolower($string);
return (in_array($string, array("true", "false", "1", "0", "yes", "no"), true));
}
But yes. The one you wrote down is the only way.
You can either use is_bool()
or as suggested on php.net:
<?php
$myString = "On";
$b = filter_var($myString, FILTER_VALIDATE_BOOLEAN);
?>
http://php.net/manual/en/function.is-bool.php
The latter one will accept strings like "on" and "yes" as true as well.