使用str_pad(PHP)递增数字 [英] Incrementing a number with str_pad (PHP)
问题描述
我正在创建一个以1001开头的递增数字.如果该数字变为1001,1002,1003 ...当它达到10时,它的格式将是1010还是10010?我需要它按顺序排列并成为1010,当达到100、1100时.
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);
推荐答案
当计数达到10时,打印的数字将为1010.如填充到一定长度您可以使用以下命令创建测试:>
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."\n");
}
当计数达到100时,打印的数字将为1100.
When your count reaches 100, the number printed will be 1100.
但是,如果要增加到1000,则将打印11000-str_pad显然不会截断匹配指定大小的字符串.
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.
这篇关于使用str_pad(PHP)递增数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!