views:

165

answers:

9

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.

Please help me. I need it. Thanks

+12  A: 
for ($i = $x ; $i <= $y; $i++)
{
    printf('%03d', $i);
}
RaYell
Thanks but it may make error cause the length of $x is dynamic. Though I fixed it with $size = strlen ($x); for ($i = $x ; $i <= $y; $i++) { printf ( '%0'.$size.'d', $i ); }But is it the right way to do this? I thought I need nested loop to make it work.But Working well. And thank you.
SHAKTI
Yes, what you described with dynamic size is ok as well.
RaYell
The `$i`, `$x` and `$y` in the loop should be normal numbers (1, 2, ...) not zero-padded (001, 002, ...). Though they get converted to regular numbers after the first iteration anyway.
DisgruntledGoat
+5  A: 

(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);

Greg
+3  A: 

try

   printf('%03d', $i)

and link to the manual

cheers

RageZ
+3  A: 

printf("%03d", $i);

Am
+5  A: 

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.

Adeel Ansari
A: 

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.

Ernelli
+1  A: 

Try using number formats

Refer to here: http://us2.php.net/manual/en/function.number-format.php

Just scroll through the bottom.

Best regards

samer
+3  A: 

use printf:

for ( $i = $x ; $i <= $y; $i++ ) {
    printf("%03d", $i);
}
Carson Myers
+1  A: 

str_pad method:

echo str_pad($i, 3, '0', STR_PAD_LEFT);
raspi