PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php怎么将数字转为字符串

青灯夜游
青灯夜游 原创
2023-01-18 10:36:03 3045浏览

4种方法:1、使用“.”字符将数字变量和空字符拼接在一起,语法“$str = $num."";”;2、在要转换的数字变量之前加上用括号括起来的目标类型“(string)”,语法“(string)$num”;3、使用strval()函数,语法“strval($num)”;4、使用strval()函数,语法“settype($num,"string");”。

本教程操作环境:windows7系统、PHP8版、DELL G3电脑

php把数字转为字符串类型

方法1:使用“.”字符将数字变量和空字符拼接在一起

“.”是字符串拼接字符,可以将两个字符串拼接为一个字符串并输出

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

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

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

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

1.png

方法2:在要转换的数字变量之前加上用括号括起来的目标类型“(string)

使用在变量之前加上用括号括起来的目标类型,可以将指定变量强制转换为指定类型,而:

  • (string):就是强制转换成字符串类型;

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

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

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

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

2.png

方法3:使用strval()函数

strval() 函数用于获取变量的字符串值,可以将数字类型的值转为字符串。

<?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;;
?>

3.png

方法4:使用settype()函数

settype():用于将变量设置为指定类型(settype() 函数会改变变量原本的类型)。

<?php
header("Content-type:text/html;charset=utf-8"); 
$num = 146;
var_dump($num);
settype($num,"string");
var_dump($num);
?>

4.png

说明:settype()函数第二个参数(设置的类型) 的值可以是:

  • "boolean" (或为"bool",从 PHP 4.2.0 起)

  • "integer" (或为"int",从 PHP 4.2.0 起)

  • "float" (只在 PHP 4.2.0 之后可以使用,对于旧版本中使用的"double"现已停用)

  • "string"

  • "array"

  • "object"

  • "null" (从 PHP 4.2.0 起)

settype()函数会影响原变量的类型。

推荐学习:《PHP视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。