views:

36

answers:

4

Hi all,

I've tried to do a number(decimal) increment which looks like 001 002 003...123,124 in a loop and couldn't find a simple solution.What I've thought now is to check out whether the number is long enough ,if not prefix it some "0".But it seems not good.Any better ideas?

Thanks.

+4  A: 
$x = 6    
$y = sprintf("%03d",$x);

http://php.net/manual/en/function.sprintf.php

phimuemue
+1  A: 
for($i=1;$i<1000;$i++){
  $number = sprintf("%03d",$i);
  echo "$number <br />";
}
oezi
+1  A: 

Two options come immediately to mind. First, try str_pad(). It does exactly what you seem to describe.

Second, you could use sprintf() as another has suggested.

Kalium
Yep, that's completely correct. On http://php.net/manual/en/function.str-pad.php someone notes, that "For number formatting (like writing numbers with leading zeroes etc.) , sprintf is much faster than str_pad.".
phimuemue
+1  A: 

If you are not sure how long the various numbers will turn out to be (e.g., they are determined dynamically and no way of knowing what they will be until afterwards), you can use the following code:

<?php

$numbers = array();

for ($i = 0; $i < 2000; $i++)
{
    $numbers[] = $i;
}

array_walk($numbers, function(&$item, $key, $len) { $item = sprintf('%0'.$len.'d', $item); }, strlen(max($numbers)));

print_r($numbers);

?>
Dan D.