How to make a counter with zero to the left

11

I need to print values like this, with leading zeros

  

00001
  00002
  00003

for($i = 00001; $i < 10000; $i++){
   validar($i);
   echo $i."\n\r";
}
    
asked by anonymous 22.11.2015 / 10:10

1 answer

12

Just use str_pad :

for($i = 1; $i < 10000; $i++){
   echo str_pad( $i, 5, '0', STR_PAD_LEFT ) . "\n";
}

Result:

00001
00002
00003
00004
00005
    ⋮

See working at IDEONE .


Parameters: input value, desired size, fill character (s), position.

See online documentation for the details of the function.

    
22.11.2015 / 10:12