Andrew Andrew - 3 months ago 14
PHP Question

How to force PHP to output a number preceded by zeros?

for ($number = 1; $number <= 16; $number++) {
echo $number . "\n";
}

This code outputs:

1
2
3
...
16


How can I get PHP to output the numbers preceded by zeros?

01
02
03
...
16

Answer

You could use sprintf to format your number to a string, or printf to format it and display the string immediatly.

You'd have to specify a format such as this one, I'd say : %02d :

  • padding specifier = 0
  • width specifier = 2
  • integer = d

(Even if you have what you want here, you should read the manual page of sprintf : there are a lot of possibilities, depending on the kind of data you are using, and the kind of output formating you want)


And, as a demo, if temp.php contains this portion of code :

<?php
for ($number = 1; $number <= 16; $number++) {
    printf("%02d\n", $number);
}

Calling it will give you :

C:\dev\tests\temp>php temp.php
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
Comments