Forcing method: 1. Add the target type enclosed in parentheses before the string variable, such as "(int)$str", "(bool)$str", "(float)$str" "; 2. Use the conversion functions intval(), floatval(), boolval(), and settype().
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php will string Force conversion to other types
#Method 1: Add the target type enclosed in parentheses before the string variable
(int), (integer): Convert to integer type;
(bool), (boolean): Convert to Boolean type;
(float), (double), (real): Convert to floating point type;
(array): Convert to array type;
(object): Convert to object type.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $int = (int)$str; echo '变量 $int 的类型为:'.gettype($int).'<br>'; $float = (float)$str; echo '变量 $float 的类型为:'.gettype($float).'<br>'; $bool = (bool)$str; echo '变量 $bool 的类型为:'.gettype($bool); ?>
2. Use the cast function
intval(): used to get the integer value of the variable;
floatval(): used to get the floating point value of the variable;
boolval(): used to get the Boolean value of a variable;
settype(): used to set a variable to a specified type (the settype() function will change the original type of the variable).
<?php header("Content-type:text/html;charset=utf-8"); $str = '123.456abc'; $int = intval($str); echo '变量 $int 的类型为:'.gettype($int).'<br>'; $float = floatval($str); echo '变量 $float 的类型为:'.gettype($float).'<br>'; $bool = boolval($str); echo '变量 $bool 的类型为:'.gettype($bool).'<br>'; $arr = settype($str,"array"); echo '变量 $str 的类型为:'.gettype($str); ?>
Description: The value of the second parameter (set type) of the settype() function can be:
"boolean" (or "bool" since PHP 4.2.0)
"integer" (or "int" since PHP 4.2.0)
"float" (only available after PHP 4.2.0, "double" used in older versions is now disabled)
"string"
"array"
"object"
"null" (Starting from PHP 4.2.0)
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to force string to other types in php. For more information, please follow other related articles on the PHP Chinese website!