2

How can I generate month leading with zero like 01-12.

Here is my code:

<?php for($m = 1;$m <= 12; $m++){ $month =  date("F", mktime(0, 0, 0, $m));?>                               
<li><a href="<?php echo site_url('agenda/'.$tgl[0].'/'.$m);?>"><?php echo $month;?></a></li><?php } ?>  

the output url is still 1-12. I want it to appear as 01-12.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
nady saptra
  • 39
  • 1
  • 6

6 Answers6

3

use sprintf

<?php echo sprintf('%02d', $month); ?>

in your snippet

<?php for($m = 1;$m <= 12; $m++): ?>    
    <li>
        <a href="<?php echo site_url("agenda/${tgl[0]}/" . sprintf('%02d', $m)); ?>">
            <?php echo date("F", mktime(0, 0, 0, $m)); ?>
        </a>
    </li>
<?php endfor; ?>
rkmax
  • 17,633
  • 23
  • 91
  • 176
2

how about using str_pad It will pad the string with a character '0' to a length of 2.

<?php 
for($m = 1;$m <= 12; $m++) { 
  $month = str_pad($m, 2, '0', STR_PAD_LEFT);
}
?>

http://php.net/manual/en/function.str-pad.php

Gavin Bruce
  • 1,799
  • 16
  • 28
1

Short and fast: (sprintf is expensive)

    $month = ($m = date('m')) < 10 ? '0' . $m : $m;
Mulli
  • 1,598
  • 2
  • 22
  • 39
0
<?php for($m = 1;$m <= 12; $m++){ $month =  date("F", mktime(0, 0, 0, $m)); if ($month < 10) $month = "0".$month; ?>
monkeyinsight
  • 4,719
  • 1
  • 20
  • 28
0

Using sprintf() you can achieve this format,

<?php echo sprintf("%02d",$month); ?>
Ranjith
  • 2,779
  • 3
  • 22
  • 41
  • thanks its helpful but a little correction :) – nady saptra Apr 13 '13 at 04:57
  • @nadysaptra : okies. It's just a logic. wherever you want you could apply. welcome – Ranjith Apr 13 '13 at 05:01
  • `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()` without `echo` every time. – mickmackusa Apr 09 '22 at 06:07
0

Try with

$month = date('m',mktime(0, 0, 0, $m));  //HERE give 'm' option       

"m" Numeric representation of a month, with leading zeros 01 through 12

GautamD31
  • 28,552
  • 10
  • 64
  • 85