Home > Article > Backend Development > How to convert string to boolean type in php
Conversion method: 1. Add the target type "(bool)" or "(boolean)" enclosed in parentheses before the conversion variable; 2. Use the boolval() function, the syntax "boolval(string) )"; 3. Use the settype() function with the syntax "settype(variable, "boolean")".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php will string Method of converting to Boolean type
Method 1: Add the target type "(bool)" or "(boolean)" enclosed in parentheses before the conversion variable
<?php header("Content-type:text/html;charset=utf-8"); $str = "123abc"; echo '变量的原类型为:'; var_dump($str); $bool = (bool)$str; echo '变量转换后的类型为:'; var_dump($bool); ?>
Output:
Method 2: Use boolval() function
boolval(): Use Used to get the Boolean value of the variable;
<?php header("Content-type:text/html;charset=utf-8"); $str = "hello"; echo '变量的原类型为:'; var_dump($str); $bool = boolval($str); echo '变量转换后的类型为:'; var_dump($bool); ?>
Output:
Method 3: Use the bsettype() function
settype(): used to set the type of a variable; the settype() function changes the type of the variable itself.
Return value: TRUE when the setting is successful, FALSE when the setting fails.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $str = "hello"; echo '变量的原类型为:'; var_dump($str); $bool = settype($str,"boolean"); echo '变量转换后的类型为:'; var_dump($str); ?>
Output:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert string to boolean type in php. For more information, please follow other related articles on the PHP Chinese website!