dongqiang2069 2014-07-17 09:22
浏览 14
已采纳

使用str_pad(PHP)递增数字[关闭]

I am creating an incrementing number starting with 1001. If the number goes 1001,1002,1003... when it reaches 10, will it be formatted like 1010 or will it be 10010? I need it to just go in order and be 1010 and when it reaches 100, 1100.

$prefix = "1"; // update the prefix here

    $number = 1;
    $number++;
    $unique = str_pad($number, 3, "0", STR_PAD_LEFT);
    $unique = $prefix . $unique;

print_r($unique);
  • 写回答

3条回答 默认 最新

  • donglijuan8227 2014-07-17 09:35
    关注

    When your count reaches 10, the number printed will be 1010. As described here, str_pad "Pads a string to a certain length with another string" You can create a test with the following:

    $prefix = "1"; // update the prefix here
    
    $number = 1;
    
    for ($number = 1; $number <= 100; $number++)
    {    
      $unique = str_pad($number, 3, "0", STR_PAD_LEFT);
      $unique = $prefix . $unique;    
      print($unique."
    ");
     }
    

    When your count reaches 100, the number printed will be 1100.

    However, if you were to go up to 1000, 11000 would be printed - str_pad apparently will not truncate the string to match the specified size.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?