dongqiang2069
2014-07-17 17: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 donglijuan8227 2014-07-17 17: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.

    点赞 评论 复制链接分享
  • duanqiu9104 duanqiu9104 2014-07-17 17:31

    With your code it will be 10010.

    It looks like you are making this more complicated than it needs to be. Why not just start with $number = 1001 and increment it and then turn it into a string?

    $number = 1001;
    $number++;
    
    $unique = strval($number);
    
    print_r($unique);
    
    点赞 评论 复制链接分享
  • dongshen5115 dongshen5115 2014-07-17 17:34

    It will be 1010, but you can test this yourself easily:

    $prefix = "1"; // update the prefix here
    
    $number = 9;
    $number++;
    $unique = str_pad($number, 3, "0", STR_PAD_LEFT);
    $unique = $prefix . $unique;
    
    print_r($unique);  // 1010
    

    The second argument of str_pad specifies padding. If padding is 3, then 1 becomes 001, 10 becomes 010, 100 becomes 100.

    点赞 评论 复制链接分享

相关推荐