dousi2029 2012-07-15 14:59
浏览 221
已采纳

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

In the following I tried $code = (string)$code; with no success, how can I convert number to string in PHP?

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

Output:

1
0

and

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

Output:

12
087326487326
08732648732
0873264873
087326487
08732648
0873264
087326
08732
0873
087
08
0
  • 写回答

3条回答 默认 最新

  • douyi1084 2012-07-15 15:02
    关注

    It's failing because it's prefixed with a 0, making PHP attempt to interpret it as an octal number, where 8 is not a valid octal digit as it parses the string, so you get 0.

    The solution is to use a (string) cast or strval(), but you need to remove the leading zero from your definition of $code.

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

    This will output (on an x64 machine):

    int(87326487326) string(11) "87326487326" string(11) "87326487326" 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败