【问题标题】:How to iterate with for loop over numbers starting with 0 in PHP? [duplicate]如何用for循环遍历PHP中以0开头的数字? [复制]
【发布时间】:2017-04-16 05:31:43
【问题描述】:

我正在尝试使用for loop 遍历以 0 开头的 8 个数字。例如,第一个数字是:00000000,我想显示接下来的 5 个数字。 到目前为止,我设法完成了某事。像这样:

<?php

     $start = 00000000;
     $number = 5;

     for ($i = $start; $i < $start + $number; $i++) {
        $url = sprintf("http://test.com/id/%08d", $i);
        echo $url . "\r\n";
     }
?>

结果:

http://test.com/id/00000000
http://test.com/id/00000001
http://test.com/id/00000002
http://test.com/id/00000003
http://test.com/id/00000004

这个例子一切都很好,但是,问题从这样一个例子开始:

<?php

         $start = 00050200;
         $number = 5;

         for ($i = $start; $i < $start + $number; $i++) {
            $url = sprintf("http://test.com/id/%08d", $i);
            echo $url . "\r\n";
         }
    ?>

for 循环产生:

http://test.com/id/00020608
http://test.com/id/00020609
http://test.com/id/00020610
http://test.com/id/00020611
http://test.com/id/00020612

虽然我期待:

http://test.com/id/00050200
http://test.com/id/00050201
http://test.com/id/00050202
http://test.com/id/00050203
http://test.com/id/00050204

【问题讨论】:

  • 在 PHP 中,以0 开头的数字是八进制。
  • 只需初始化 $start=0,因为 sprintf 正在为您进行格式化。

标签: php loops for-loop iteration


【解决方案1】:

您得到其他数字的原因是前导零使您的数字变为八进制。所以你从设置$start = 00050200;开始,这使得$start是八进制的。

只需删除这些前导零,代码就可以了。

【讨论】:

    【解决方案2】:

    它不起作用,因为以 0 开头的数字被解释为八进制数。来自Integers page of the PHP Documentation(强调我的):

    整数可以指定为十进制(以 10 为底)、十六进制(以 16 为底)、 八进制(以 8 为基数)或二进制(以 2 为基数)表示法,前面可选 符号(- 或 +)。

    从 PHP 5.4.0 开始提供二进制整数文字。

    要使用八进制表示法,请在数字前加上 0(零)。使用 十六进制表示法在数字前加 0x。使用二进制 数字前加 0b 的符号。

    只需使用:

     $start = 50200;
    

    在代码的开头,一切都应该正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 2020-10-31
      • 2012-09-29
      • 1970-01-01
      相关资源
      最近更新 更多