Forced type conversion method: 1. Use strval() function, syntax "strval(variable)"; 2. Use settype() function, syntax "settype(data value, "string")"; 3. Add "(string)" before the variable of conversion type, the syntax is "(string) variable".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php will force the variable type to string (character String) There are three methods:
Use the conversion function strval()
Use the conversion function settype()
Add the target type enclosed in parentheses before the variable to be converted (string)
Method 1: Use the conversion function strval ()
strval() function is used to obtain the string value of a variable. It is often used to convert data such as integer and floating point types into string types.
Syntax: strval ($var)
strval() function cannot be used for conversion of arrays or objects.
Example:
<?php $num=3.21; var_dump($num); var_dump(strval($num)); $bool=TRUE; var_dump($bool); var_dump(strval($bool)); $bool=FALSE; var_dump($bool); var_dump(strval($bool)); ?>
Method 2: Use the conversion function settype()
settype ( $var,$type)
function is used to set variable $var
to the specified data type $type
. ($type can be boolean (bool), integer (int), float (double), string, array, object, null).
You only need to set the parameter $type to "string"
to convert the specified variable to a string type.
Note: The settype() function will modify the original attributes; if the type is set successfully, it returns TRUE and if it fails, it returns FALSE.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $num = 3.1415; echo '原变量类型为:' . gettype($num) . '<br>'; $str = strval($num); echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; $num = 31415; echo '原变量类型为:' . gettype($num) . '<br>'; $str = strval($num); echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; $bool = TRUE; echo '原变量类型为:' . gettype($bool) . '<br>'; $str = strval($bool); echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; ?>
Method 3: Add the target type enclosed in parentheses before the variable to be converted (string )
<?php header("Content-type:text/html;charset=utf-8"); $num = NULL; echo '原变量类型为:' . gettype($num) . '<br>'; $str = (string)$num; echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; $num = 123.54; echo '原变量类型为:' . gettype($num) . '<br>'; $str = (string)$num; echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; $bool = TRUE; echo '原变量类型为:' . gettype($bool) . '<br>'; $str = (string)$bool; echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to force type conversion to str string in php. For more information, please follow other related articles on the PHP Chinese website!