9
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
Andrew
  • 227,796
  • 193
  • 515
  • 708

9 Answers9

19

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
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
5

You can use str_pad().

str_pad — Pad a string to a certain length with another string

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
4

The old-fashioned way: $str = sprintf("%02.2d", $number); or use printf("%02.2d\n", $number); to print it immediately.

Chris
  • 136
  • 2
3
for ($number = 1; $number <= 16; $number++) {
  echo sprintf("%02d", $number) . "<br>";
}
Keith Maurino
  • 3,374
  • 10
  • 40
  • 48
0

if($number < 10) echo '0' . $number;

I know there are a lot better answers than this here, but I though't I'd leave it to show there's more than one way to skin a cat...

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
0

Quick method:

<?php
for ($number = 1; $number <= 16; $number++)
{    
    if($number < 10)
        echo "0".$number."\n";
    else
        echo $number."\n";
}
?>
Urda
  • 5,460
  • 5
  • 34
  • 47
  • I'm going to go out on a limb here, I don't think efficiency is OP's highest worry. But hey it was just a simple answer for a simple question. Sorry your nose is too high up in the clouds at this point though! – Urda Feb 19 '10 at 01:51
0

Lets keep it simple. Use str_pad

echo str_pad(1, 6 , "0");

produces 000006

ronaldosantana
  • 5,112
  • 4
  • 22
  • 28
0

echo ($number < 10) ? (0 . $number) : $number;

-1
<?php
  for ($number = 1; $number <= 16; $number++) 
  { 
    if($number<10)
      echo '0';
    echo $number . "<br>"; 
  }
?>
VolkerK
  • 95,432
  • 20
  • 163
  • 226
Dave
  • 1,065
  • 2
  • 10
  • 16