Home >Backend Development >PHP Problem >How to convert string to boolean type in php
Method: 1. Add "(bool)" or "(boolean)" before the variable to be converted to force conversion to boolean type; 2. Use the boolval() function with the syntax "boolval(value)" ;3. Use the settype() function, the syntax is "settype(value, "boolean")".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
1. Forced type conversion-- Prepend the target type enclosed in parentheses (bool)
or (boolean)
before the variable to be converted. Example:
<?php $bool1 = (bool) 'ciao'; $bool2 = (boolean) '0'; var_dump($bool1); var_dump($bool2); ?>
Rendering:
2. Use boolval() function
boolval function is used to obtain The Boolean value of the variable.
Example:
<?php echo '0: '.(boolval(0) ? 'true' : 'false')."\n"; echo '42: '.(boolval(42) ? 'true' : 'false')."\n"; echo '0.0: '.(boolval(0.0) ? 'true' : 'false')."\n"; echo '4.2: '.(boolval(4.2) ? 'true' : 'false')."\n"; echo '"": '.(boolval("") ? 'true' : 'false')."\n"; echo '"string": '.(boolval("string") ? 'true' : 'false')."\n"; echo '"0": '.(boolval("0") ? 'true' : 'false')."\n"; echo '"1": '.(boolval("1") ? 'true' : 'false')."\n"; echo '[1, 2]: '.(boolval([1, 2]) ? 'true' : 'false')."\n"; echo '[]: '.(boolval([]) ? 'true' : 'false')."\n"; echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n"; ?>
Output:
0: false 42: true 0.0: false 4.2: true "": false "string": true "0": false "1": true [1, 2]: true []: false stdClass: true
3. Use the general type conversion function settype(mixed var,string type)
<?php $str="123.9sdc"; $int=settype($str,"boolean"); var_dump($int); var_dump($str); echo "<hr>"; $str=""; $int=settype($str,"boolean"); var_dump($int); var_dump($str); ?>
Output:
The settype() function is used to set the type of a variable.
Syntax
bool settype ( mixed &$var , string $type )
Set the type of variable var to type.
Parameters | Description |
---|---|
##var | To be converted Variables. The possible values of|
type |
##type are:
|
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!