开发者

How to force PHP to output a number preceded by zeros? [duplicate]

开发者 https://www.devze.com 2022-12-20 10:05 出处:网络
This question already has answers here: How to pad single-digit numbers with a leading 0 (7 answers) Closed 8 months ago.
This question already has answers here: How to pad single-digit numbers with a leading 0 (7 answers) Closed 8 months ago.
for ($number = 1; $number &l开发者_如何学Got;= 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


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


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.


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


for ($number = 1; $number <= 16; $number++) {
  echo sprintf("%02d", $number) . "<br>";
}


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...


Quick method:

<?php
for ($number = 1; $number <= 16; $number++)
{    
    if($number < 10)
        echo "0".$number."\n";
    else
        echo $number."\n";
}
?>


Lets keep it simple. Use str_pad

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

produces 000006


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


<?php
  for ($number = 1; $number <= 16; $number++) 
  { 
    if($number<10)
      echo '0';
    echo $number . "<br>"; 
  }
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消