turn string into bool php code example
Example 1: cast to boolean php
/** filter_var - Filters a variable with a specific filter **/
$boolvar = filter_var('true', FILTER_VALIDATE_BOOLEAN);
/** boolval - Get the boolean value of a variable PHP 5 >= */
$boolvar = boolval ('true');
// And literally with a ternary operator but I can't recommend it
$boolvar = ($string === 'true') ? true: false;
/** We can convert any variable to boolean
--- using the (bool) or (boolean) keyword -----
*** But we are talking about conversion not casting ***
- So any String whose length is greater than 0 is true
- and any number other than 0 is true
**/
echo $boolvar = (bool)1; //return true
echo $boolvar = (bool)"true"; //return true
echo $boolvar = (bool)"false"; //return true
echo $boolvar = (bool)0; //return false
echo $boolvar = (bool)""; //return false
var_dump((bool) 0);//return false
var_dump((bool) "");//return false
Example 2: php convert to boolean
// (PHP 5 >= 5.5.0, PHP 7)
// boolval — Get the boolean value of a variable
boolval ( mixed $var ) : bool
// Returns the boolean value of var.