Page 1 of 1

Increment with leading zeros

Posted: Fri Jun 15, 2007 10:20 am
by GeXus
Say I wanted to start with the following number 001 and increment it by 1.. so 002, 003, 010, 011, 100, 101, and so on...

How would I do this??

Thank you!!

Posted: Fri Jun 15, 2007 10:30 am
by Gente

Code: Select all

<?php
function format_number($i)
{
  return substr('000'+$i, -3);
}

$i = 35;
echo format_number($i);
?>

Posted: Fri Jun 15, 2007 10:34 am
by GeXus
Cool thanks.. I also just found that this works too

Code: Select all

$i = 1
$n = sprintf("%03d",$i);

Posted: Fri Jun 15, 2007 10:36 am
by Gente
Sorry, sure

Code: Select all

return substr('000'.$i, -3);
...
Friday's evening :)

Posted: Fri Jun 15, 2007 11:37 am
by Benjamin
I would just increment it as a regular int and use str_pad to prepend zeros.