4

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?

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
  • Leading "0"s mean nothing to a *number*: they are simply an artifact of a given *text representation* (it can mean octal or just be padding, as in the post). –  Aug 04 '11 at 18:16

6 Answers6

7

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

hughes
  • 5,595
  • 3
  • 39
  • 55
2
if ($list_day < 10)
  echo "0" . $list_day;
else
  echo $list_day;
Pepe
  • 6,360
  • 5
  • 27
  • 29
1
printf("%02d",$listday);


printf("%02d",3);  //prints 03
RiaD
  • 46,822
  • 11
  • 79
  • 123
1
echo sprintf('%02d',$list_day);
Timur
  • 6,668
  • 1
  • 28
  • 37
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` every time. – mickmackusa Apr 08 '22 at 04:23
1

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>";
}
Brad Mace
  • 27,194
  • 17
  • 102
  • 148
  • In the first method you'd be incrementing a string after the first loop. PHP might just interpret `"02"` as the integer `2` but I wouldn't count on it. – JJJ Aug 04 '11 at 18:21
  • @Juhana - String concatenation is done with `.` in PHP; when using `+` it autoconverts strings to integers correctly. – Brad Mace Aug 04 '11 at 18:24
  • That's what I thought :) You should start with $list_day = "01" then, though. – JJJ Aug 04 '11 at 18:33
  • Instead of calling `sprintf()` inside of `print`, just call `printf()` and write all of the literal strings inside the first parameter of `printf()`. – mickmackusa Apr 08 '22 at 04:24
0
if($list_day < 10)
    $new_day = '0'.$list_day;
else
    $new_day = $list_day;
Jacek Kaniuk
  • 5,229
  • 26
  • 28
  • 1
    This will probably mess up the loop. It's better not to touch the original variable. – JJJ Aug 04 '11 at 18:16