Iterating over numbers with leading zeroes with a `for` loop [duplicate]
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;
精彩评论