0

I keep having issues on the last day of the month, other than that this code works just fine to display all 12 months starting at the current month. On the last day of the month I get duplicates of some months and others do not show at all. Any help would be appreciated. Thanks.

<select id="month" name="month">


<?php

//lists months

    for ($i = 0; $i <= 11; ++$i) 
        {
            $time = strtotime(sprintf('+%d months', $i));
            $value = date('m', $time);
            $label = date('F', $time);

//if month is set stay on that month

            if($month==$value)
                { printf('<option value="%s" selected="selected">%s</option>' , $value, $label);
                }
            else
                {printf('<option value="%s">%s</option>', $value, $label);}
        }

?>

//first month shows instead of blank

    $("#target option:first")

</select>
2
  • where are you setting the value for $month ? Commented Aug 1, 2013 at 16:57
  • also, can you check if you are getting correct value for $time for different cases ? Commented Aug 1, 2013 at 17:00

2 Answers 2

1

You may be running into an issue where from the current day X months later is skipping over a month. Instead of

   strtotime(sprintf('+%d months', $i));

Try using

    strtotime(sprintf('first day of +%d month', $i));
Sign up to request clarification or add additional context in comments.

Comments

0
<?php

    function months($selctedMonth='january'){

        $months='<select name="month" size="1">';
        for ($i = 12; $i > 0; $i--) {
            $time = strtotime(sprintf('-%d months', $i));   
            $label = date('F', $time); 
            $selctedM = strtolower($selctedMonth) == strtolower($label) ? 'selected' : '';
            $months.="<option value='$label'  $selctedM >$label</option>";
        }  
        $months.="</select>";
        return $months;
    }

     echo months(); 


?>

By default, January will be displayed as selected.

if you write <?php echo months('march'); ?> then march will be selected by default.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.