Reputation: 45737
I have a select box with the following values ( months of the year ):
<label for="select_month">Month: </label>
<select id="select_month" name="month">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
What I would like to achieve is to get with PHP the current month, and make that as default-selected option in my select box.
How can I do that with a clean code?
Upvotes: 2
Views: 7562
Reputation: 8266
Uses a similar structure to Pratt's answer, but uses the double-digit month values (like you had in your example). It uses date('m') instead of date('n') and since there doesn't appear to be any way to get leading zeros in PHP range, I used an array.
<select name="month">
<?php foreach(array('01','02','03','04','05','06','07','08','09','10','11','12') as $m) : ?>
<option value="<?php echo $m; ?>" <?php if (date('m') == $m) { echo 'selected="selected"'; } ?>>
<?php echo $m ?>
</option>
<?php endforeach; ?>
</select>
Upvotes: 1
Reputation: 1678
Here is my two cents:
<label for="select_month">Month: </label>
<select id="select_month" name="month">
<?php
for($i = 1; $i <= 12; $i++) {
$isCurrentMonth = ($i == intVal(date("m"))) ? 'true': 'false';
echo "<option value=\"$i\" selected=\"$isCurrentMonth\">$i</option>\n";
}
?>
</select>
Upvotes: 1
Reputation: 1608
Perhaps something like this?
<select name="month">
<?php foreach(range('1', '12') as $m) : ?>
<option value="<?php echo $m; ?>" <?php if (date('n') == $m) { echo 'selected="selected"'; } ?>>
<?php echo $m ?>
</option>
<?php endforeach; ?>
</select>
Upvotes: 2
Reputation: 13687
for ($i = 1; $i <= 12; $i++)
(
$month = ($i < 10) ? '0'.$i : $i;
echo '<option value="'.$month.'"';
if ($i == date("n")) echo ' selected="selected"';
echo '>'.$month.'</option>';
)
I can't test this as I'm on my phone, but that should do the trick.
Upvotes: 4
Reputation: 2381
<option value="01" <?php echo (1 == date("n") ? 'selected="selected"' : ''); ?>>01</option>
This will have to be done for every option - a for loop might be nice in this situation.
Upvotes: 0