How to make a counter with zero left

Asked

Viewed 310 times

11

I need to print values like this, with zeros on the left

00001
00002
00003

for($i = 00001; $i < 10000; $i++){
   validar($i);
   echo $i."\n\r";
}

1 answer

12


Just use str_pad:

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

Upshot:

00001
00002
00003
00004
00005
    ⋮

See working on IDEONE.


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

See the online documentation to know the details of the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.