开发者

Iterating over numbers with leading zeroes with a `for` loop [duplicate]

This question already has answers here: How to pad single开发者_StackOverflow中文版-digit numbers with a leading 0 (7 answers) Closed 12 months ago.

I'm working on a calendar site and need to change the following code to show 0 before the value of $list_day if it's a single digit number.

for($list_day = 1; $list_day <= $days_in_month; $list_day++):

How should I go about doing this?


When you're printing it, use sprintf("%02d", $list_day) to pad it with a zero.


if ($list_day < 10)
  echo "0" . $list_day;
else
  echo $list_day;


printf("%02d",$listday);


printf("%02d",3);  //prints 03


echo sprintf('%02d',$list_day);


You could do this as

for ($list_day = "01"; $list_day <= $days_in_month; $list_day = sprintf("%02d", $list_day + 1))

but it's usually done like

for ($list_day = 1; $list_day <= $days_in_month; $list_day++) {
    print "<div>" . sprintf("%02d", $list_day) . "...</div>";
}


if($list_day < 10)
    $new_day = '0'.$list_day;
else
    $new_day = $list_day;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜