Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a HTML select form to select the day/month/year, and this is generated with PHP. My for loop, for example with the month, looks like this:

$html="<select name=\"".$name."month\">";       
for($i=1;$i<=12;$i++)
 {$html.="<option value='$i'>$months[$i]</option>";}
$html.="</select> ";

I can't seem to figure out how to set a "default" value to the current month while retaining all of the prior months in the dropdown (I can just set $i=date("n"), but then I lose the ability to select any prior month).

Does anybody know a simple way of setting the default value to be the current day? Thank you very much!

share|improve this question
+1 to the answer that fits the question... but you could do it in Javascript. – ring0 yesterday
Thanks! I didn't choose the javascript method because of support and speed. – Dave Chen yesterday

2 Answers

up vote 4 down vote accepted

Try this:

<?php

$currentMonth = date("m");

$html = "<select name=\"" . $name . "month\">";
for ($i = 1; $i <= 12; $i++) {
    if ($i == $currentMonth) {
        $html .= "<option selected='selected' value='$i'>$months[$i]</option>";
    } else {
        $html .= "<option value='$i'>$months[$i]</option>";
    }
}
$html .= "</select> ";

echo $html;

?>
share|improve this answer
i am late :( it was easy question – web2students.com yesterday
I'm sure it was quite easy, but for someone that barely knows PHP, I couldn't figure it out with an hour of troubleshooting. Nothing game up in Google for "default value in for loop". Thank you very much for this answer! – Paul yesterday
@paul i wanted to say, if i had answered before him, i would have got +1 . i know it's childish nature dying for +1 but i have this nature – web2students.com yesterday

Psul - look at using selected (see http://www.w3schools.com/tags/att_option_selected.asp) and changed the code to add this when the loop reaches the month.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.