views:

94

answers:

3

Here is my code:

<?php
$variable1 = 00001;
$variable2 = (sprintf('%04d', $variable1 + 1));
echo $variable2;
?>

How come the outcome of this code is "0002" and not "00002"? in other words it is missing a 0.

+7  A: 

The 4 in %04d sets the total width of the printed value

Trent
Oh I see, thank-you very much :)
Ryan
+4  A: 

the number in the first parameter is the "total number of characters" not the number of zeroes to use in padding. What you are looking for is %05d instead.

Rich
+1  A: 

A more interesting question is why does the following print '0009' instead of '0011'?

<?php
$var = 0010;
$str = sprintf('%04d', $var+1);
echo $str;
?>

So why are you using octal representation anyway? I'm just curious.

D.Shawley