Answers for "php cast boolean comparison"

PHP
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
Posted by: Guest on December-20-2020

Browse Popular Code Answers by Language