问题
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);
回答1:
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");
}
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:
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
.
回答3:
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);
来源:https://stackoverflow.com/questions/24809811/incrementing-a-number-with-str-pad-php