Search code examples
phpdatemktime

How would I fix the last day of the month errors that result with this php code?


The code below is what I'm using for a website menu which moves the link for the current month's page to the top of the link list on the change of the month.

But this fails on the 31st of some months, such as April; I get two links to the same month for most of the links. I've read through the issues with the way php generates dates, but can't figure out how to change this code.

Anyone php Ph.D's want to take a stab at it? Thanks

<?php $month1 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+1 , date('d'), date('Y'))));
$month2 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+2 , date('d'), date('Y'))));
$month3 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+3 , date('d'), date('Y'))));
$month4 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+4 , date('d'), date('Y'))));
$month5 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+5 , date('d'), date('Y'))));
$month6 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+6 , date('d'), date('Y'))));
$month7 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+7 , date('d'), date('Y'))));
$month8 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+8 , date('d'), date('Y'))));
$month9 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+9 , date('d'), date('Y'))));
$month10 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+10 , date('d'), date('Y'))));
$month11 = (date('F', mktime(date('H'), date('i'), date('s'), date('m')+11 , date('d'), date('Y')))); ?>

<a href="http://mydomain.com/<?php echo strtolower(date('F')); ?>/" title="<?php echo ucfirst(date('F')); ?>"><?php echo (date('F')); ?></a><br />

<a href="http://mydomain.com/<?php echo strtolower($month1); ?>/" title="<?php echo $month1; ?>"><?php echo $month1; ?></a><br />

...(2 through 10)...

<a href="http://mydomain.com/<?php echo strtolower($month11); ?>/" title="<?php echo $month11; ?>"><?php echo $month11; ?></a><br />

Solution

  • <?php

    $current_month = date('n');
    $MONTHS = array();
    for ($m=0; $m<12; $m++) {
      $display_month = $m + $current_month;
      $MONTHS[] = date('F',mktime(1,1,1,$display_month,1,date("Y")));
    }
    foreach ($MONTHS as $month) {
      echo "
        <a
          href=\"http://mydomain.com/".strtolower($month)."\"
          title=\"$month\">$month</a><br />";
    }
    ?>