Conversion method: 1. Use strval() function, syntax "strval(data value)"; 2. Use settype() function, syntax "settype(data value, "string")"; 3. Use sprintf() function, syntax "sprintf(formatting mode, data value)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php will change the data type Convert to string type
#Method 1: Use strval() function
The strval() function is used to obtain the string value of a variable.
<?php $num=3.21; var_dump($num); $str=strval($num); var_dump($str); ?>
Method 2: Use the settype() function
settype ($var,$type)
The function is used to set the variable $var
to the specified data type $type
.
<?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>'; ?>
The value of $type can be:
"boolean" (or "bool" from PHP since 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" (from PHP 4.2.0)
Method 3: Use the sprintf() function
The sprintf() function writes the formatted string into a variable.
<?php $num=12; var_dump($num); $str1=sprintf("%.1f",$num); var_dump($str1); $str2=sprintf("%.2f",$num); var_dump($str2); $str3=sprintf("%.3f",$num); var_dump($str3); $str4=sprintf("%.4f",$num); var_dump($str4); ?>
Description: sprintf() function
sprintf(format,arg1,arg2,arg++)
Parameters | Description |
---|---|
format | Required. Specifies a string and how to format variables within it. Possible format values:
Additional format value. Must be placed between % and a letter (such as %.2f):
Note: If multiple above format values are used, they must be used in the order above and cannot be disrupted. |
arg1 | Required. Specifies the parameters to be inserted at the first % sign in the format string. |
arg2 | Optional. Specifies the parameter to be inserted into the format string at the second % sign. |
arg | Optional. Specifies the parameters to be inserted into the format string at the third, fourth, etc. % symbols. |
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to convert data type to string type in php. For more information, please follow other related articles on the PHP Chinese website!