Cast string to boolean PHP

> Convert string to boolean

Description
Cast string to boolean


$val = (bool)"";        // false
$val = (bool)"0";       // false
$val = (bool)"1";       // true

$val = (bool)"foo";     // true
$val = (bool)"false";   // true  <--------------
$val = (bool)"true";    // true

$val = (boolean)"foo";  // same as (bool), true
Only the empty string, and the string "0" are considered false.

$str = "true";
$val = ($str === 'true'); // true
$str = "True"
$val = ($str === 'true') ? true : false; // false
$val = (strtolower($str) === 'true') ? true : false; // true
filter_var('true', 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('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

SEE ALSO