sprintf outcome problem
-
05-09-2019 - |
Question
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.
Solution
The 4 in %04d sets the total width of the printed value
OTHER TIPS
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.
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow