1

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.

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.