PHP is a typeless language, which can change the type of variables at will during execution. One of the basic data types is Boolean. The Boolean type has only two values, true and false.
In some cases, it is necessary to convert bool type variables to other data types, or to convert other data types to bool type. In PHP, these conversions can be accomplished by casting or using built-in functions.
1. Convert other data types to bool type
In PHP, you can use the following rules to convert other data types to bool type:
The following is a PHP code example:
$var1 = 0; $var2 = 1.23; $var3 = " "; $var4 = "string"; $var5 = array(); $var6 = new stdClass(); $var7 = NULL; var_dump((bool)$var1); // false var_dump((bool)$var2); // true var_dump((bool)$var3); // false var_dump((bool)$var4); // true var_dump((bool)$var5); // false var_dump((bool)$var6); // true var_dump((bool)$var7); // false
2. Convert the bool type to other data types
In PHP, you can use The following rules convert the bool type to other data types:
The following is a sample PHP code:
$bool1 = true; $bool2 = false; echo (int)$bool1; // 1 echo (int)$bool2; // 0 echo (string)$bool1; // "1" echo (string)$bool2; // "" echo (float)$bool1; // 1.0 echo (float)$bool2; // 0.0
In addition to casting, you can also use built-in functions for type conversion.
3. Use built-in functions for type conversion
intval() function can convert a string Convert to an integer value. If the string starts with a number, it is converted directly to an integer, otherwise 0 is returned.
$str = "123.45abc"; echo intval($str); // 123
floatval() function can convert a string to a floating point value.
$str = "123.45abc"; echo floatval($str); // 123.45
strval() function can convert a value to a string type.
$val = 12345; echo strval($val); // "12345"
settype() function can convert a variable to a specified type. The first parameter of this function is the variable to be converted, and the second parameter is the type to be converted.
$str = "123.45abc"; settype($str, "float"); echo $str; // 123.45
To sum up, it is very simple to implement data type conversion in PHP. Proficient in PHP type conversion techniques can improve the readability and expressiveness of your code.
The above is the detailed content of How to convert value to bool type in php. For more information, please follow other related articles on the PHP Chinese website!