在 php 中将数字转换为字符串


Convert number to string in php

在下面我尝试了$code = (string)$code;但没有成功,如何在PHP中将数字转换为字符串?

$code = 087326487326;
$strlen = strlen($code);
print $strlen."<br/>";
for ($i = $strlen; $i >= 0; $i--) {
  print substr($code, 0, $i)."<br/>";
}

输出:

1
0

$code = '087326487326';
$strlen = strlen($code);
print $strlen."<br/>";
for ($i = $strlen; $i >= 0; $i--) {
  print substr($code, 0, $i)."<br/>";
}

输出:

12
087326487326
08732648732
0873264873
087326487
08732648
0873264
087326
08732
0873
087
08
0

它失败了,因为它以0为前缀,使PHP尝试将其解释为八进制数,其中8不是有效的八进制数字,因为它解析字符串,所以你会得到0

解决方案是使用 (string) 强制转换或strval() ,但您需要从 $code 的定义中删除前导零。

$code = 87326487326;
var_dump( $code, (string) $code, strval( $code));

这将输出(在 x64 计算机上(:

int(87326487326) string(11) "87326487326" string(11) "87326487326" 

我喜欢这种类型的杂耍方式,如果你有的话。

$code = 087326487326;

要将其转换为字符串,您所要做的就是:

$code = "$code";

编辑

对不起,有点分心,我测试错了。上面说的没错,领先零是一场灾难。怎么不去掉它,以后再补号?

你可以像这样使用类型转换

 $code = (string)58963245874;

为了检查它,你打印它的类型,如下所示

 echo gettype($code);
您可以使用

以下函数在字符串中转换:

echo strval($code);