简体   繁体   中英

PHP Creating select box starting from current month

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?

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.

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>

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>

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>
<option value="01" <?php echo (1 == date("n") ? 'selected="selected"' : ''); ?>>01</option>

这必须针对每个选项进行 - 在这种情况下for循环可能会很好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM