Home >Backend Development >PHP Problem >How to convert numbers to string in php
4 methods: 1. Use the "." character to splice the numeric variable and the empty character together, the syntax is "$str = $num."";"; 2. Add before the numeric variable to be converted The target type enclosed in parentheses is "(string)", the syntax is "(string)$num"; 3. Use the strval() function, the syntax is "strval($num)"; 4. Use the strval() function, the syntax is " settype($num,"string");".
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php put the numbers Convert to string type
#Method 1: Use the "." character to splice numeric variables and null characters together
"." is String splicing characters, you can splice two strings into one string and output
<?php header("Content-type:text/html;charset=utf-8"); $num = 12354; echo '原变量类型为:' . gettype($num) . '<br>'; $str = $num.""; echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; $num = 123.54; echo '原变量类型为:' . gettype($num) . '<br>'; $str = $num.""; echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; ?>
Method 2: Add with before the numeric variable to be converted Parenthesized target type "(string)
"
Use the parenthesized target type before the variable to force the specified variable to the specified type, And:
(string)
: It is forced to convert to string type;
<?php header("Content-type:text/html;charset=utf-8"); $num = 123.54; echo '原变量类型为:' . gettype($num) . '<br>'; $str = (string)$num; echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; $num = 12354; echo '原变量类型为:' . gettype($num) . '<br>'; $str = (string)$num; echo '转换后的变量类型为:' . gettype($str) . '<br><br>'; ?>
Method 3: Use the strval() function
The strval() function is used to obtain the string value of a variable and can convert a numeric value into a string.
<?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>'; ?>
Method 4: Use the settype() function
settype(): used to set the variable to the specified type (settype () function will change the original type of the variable).
<?php header("Content-type:text/html;charset=utf-8"); $num = 146; var_dump($num); settype($num,"string"); var_dump($num); ?>
Explanation: 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" (Since PHP 4.2.0) The
#settype() function affects the type of the original variable.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert numbers to string in php. For more information, please follow other related articles on the PHP Chinese website!