Search code examples
phpgenerator

generate month leading with zero php


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.


Solution

  • 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; ?>