How can I convert string to boolean
?
$string = 'false'; $test_mode_mail = settype($string, 'boolean'); var_dump($test_mode_mail); if($test_mode_mail) echo 'test mode is on.';
it returns,
boolean true
but it should be boolean false
.
Use filter_var() function to convert string to boolean value. Approach using PHP filter_var() Function: The filter_var() function is used to filter a variable with specified filter. This function is used to both validate and sanitize the data.
Converting to boolean ¶ To explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument. See also Type Juggling.
PHP uses the bool type to represent boolean values. To represent boolean literals, you can use the true and false keywords. These keywords are case-insensitive.
The boolean values are called true and false in php. In the case of true , the output is 1 . While with the false , it does not show any output. It is worth noting that the browser always renders these values in strings.
This method was posted by @lauthiamkok in the comments. I'm posting it here as an answer to call more attention to it.
Depending on your needs, you should consider using filter_var()
with the FILTER_VALIDATE_BOOLEAN
flag.
filter_var( true, FILTER_VALIDATE_BOOLEAN); // true filter_var( 'true', FILTER_VALIDATE_BOOLEAN); // true filter_var( 1, FILTER_VALIDATE_BOOLEAN); // true filter_var( '1', FILTER_VALIDATE_BOOLEAN); // true filter_var( 'on', FILTER_VALIDATE_BOOLEAN); // true filter_var( 'yes', FILTER_VALIDATE_BOOLEAN); // true filter_var( false, FILTER_VALIDATE_BOOLEAN); // false filter_var( 'false', FILTER_VALIDATE_BOOLEAN); // false filter_var( 0, FILTER_VALIDATE_BOOLEAN); // false filter_var( '0', FILTER_VALIDATE_BOOLEAN); // false filter_var( 'off', FILTER_VALIDATE_BOOLEAN); // false filter_var( 'no', FILTER_VALIDATE_BOOLEAN); // false filter_var('asdfasdf', FILTER_VALIDATE_BOOLEAN); // false filter_var( '', FILTER_VALIDATE_BOOLEAN); // false filter_var( null, FILTER_VALIDATE_BOOLEAN); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With