I'd like to increment a value in a 3-digits format.
For example:
$start_value = 000;
while () {
do something;
$start_value++;
}
In this way I have this result:
$start_value = 000;
$start_value = 1;开发者_StackOverflow中文版
$start_value = 2;
$start_value = 3;
and so on
instead of '001', '002', '003'
How I can accomplish this result?
Using sprintf
you can accomplish this with:
echo sprintf("%03d", $start_value++) . "<br>";
Hopefully that is what you were after.
Implementing it with your code:
$start_value = 000;
while () {
do something;
$start_value = sprintf("%03d", $start_value++);
}
You are making a big mistake here. 000
in code is an octal number. Any literal number starting with a 0 in many programming languages is considered an octal literal. If you want to store 000, you need a string, not a number.
$start_value = "000";
while((int) $start_value /*--apply condition --*/) {
do something;
$start_value = str_pad((int) $start_value+1, 3 ,"0",STR_PAD_LEFT);
}
It goes like this. In PHP there is no concept of datatypes everything is determined in runtime based on where and how it is used.
<?php
$start_value = 000;
while ($start_value < 10) {
//your logic goes here
$start_value++;
printf("[%03s]\n",$start_value);
}
?>
Output : [001] [002] [003] [004] [005] [006] [007] [008] [009] [010]
So you can do all the calculation. Where ever you want to print the value, you can use printf with format specifiers.!! Hope it helps.
精彩评论