Question
I want to count with 0. I means if
$x = 002 $y = 999
Now I want to count it by keep the 00.
for ( $i = $x ; $i <= $y; $i++ )
{
echo $i;
}
but it echo - 002, 3, 4, 5
I want it to count by keep the 00. as like 005, 006, 007, 008, 009, 010, 011, 012.
Solution
for ($i = $x ; $i <= $y; $i++)
{
printf('%03d', $i);
}
OTHER TIPS
(s)printf is your friend for this one, there's plenty of useful examples on the manual-page, but you'd want:
printf('%03d', $i);
The idea is you don't count it like that, you just show it like that. I hope you understand that 00 is just for presentation only. Cheers.
use printf:
for ( $i = $x ; $i <= $y; $i++ ) {
printf("%03d", $i);
}
printf("%03d", $i);
Try using number formats
Refer to here: http://us2.php.net/manual/en/function.number-format.php
Just scroll through the bottom.
Best regards
str_pad method:
echo str_pad($i, 3, '0', STR_PAD_LEFT);
You cannot do that if $i is an integer. The first time you assign $i it is stored as a string, after you do $i++ its converted to an integer.
If you must maintain the original format, treat $i as a string and do all arithmetic on $i using custom functions, not the build in integer arithmetic.
The easiest solution is to let $i be an integer and prepend leading zeros when you output $i.