Home >Backend Development >PHP Problem >How to convert numbers to string type in php

How to convert numbers to string type in php

青灯夜游
青灯夜游Original
2021-12-08 10:49:597306browse

php method to convert numbers to strings: 1. Add the target type "(string)" enclosed in parentheses before the numeric variable to be converted, the syntax is "(string)$num"; 2 , use strval() function, syntax "strval($num)".

How to convert numbers to string type in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php converts numbers For string type

#Method 1: Add the target type enclosed in parentheses "(string)"# before the numeric variable to be converted.

## You can coerce a specified variable to a specified type by preceding the variable with the target type enclosed in parentheses, whereas:

  • ( string): It is forced to convert to string type;

  • <?php
    header("Content-type:text/html;charset=utf-8");
    $num = 12354;
    echo &#39;原变量类型为:&#39; . gettype($num) . &#39;<br>&#39;;
    
    $str = (string)$num;
    echo &#39;转换后的变量类型为:&#39; . gettype($str) . &#39;<br><br>&#39;;
    
    $num = 123.54;
    echo &#39;原变量类型为:&#39; . gettype($num) . &#39;<br>&#39;;
    
    $str = (string)$num;
    echo &#39;转换后的变量类型为:&#39; . gettype($str) . &#39;<br><br>&#39;;
    ?>

How to convert numbers to string type in php

##Method 2: Use strval() function

strval() function is used to get the string value of a variable.

<?php
header("Content-type:text/html;charset=utf-8");
$num = 3.1415;
echo &#39;原变量类型为:&#39; . gettype($num) . &#39;<br>&#39;;

$str = strval($num);
echo &#39;转换后的变量类型为:&#39; . gettype($str) . &#39;<br><br>&#39;;

$num = 31415;
echo &#39;原变量类型为:&#39; . gettype($num) . &#39;<br>&#39;;

$str = strval($num);
echo &#39;转换后的变量类型为:&#39; . gettype($str) . &#39;<br><br>&#39;;
?>

How to convert numbers to string type in php Recommended learning: "

PHP Video Tutorial

"

The above is the detailed content of How to convert numbers to string type in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn