简体   繁体   中英

select menu with current month until end of the year

How do you make a select date menu using the current month until the end of the year?

For example... if displayed the drop down today it would show September to December only as options to the user.

This is the code I have so far but it shows months prior to September as well.

    <?php 
$curr_month = date("m");
$month = array (1=>"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$select = "<select name=\"month\">\n";
foreach ($month as $key => $val) {
    $select .= "\t<option val=\"".$key."\"";
    if ($key == $curr_month) {
        $select .= " selected=\"selected\">".$val."</option>\n";
    } else {
        $select .= ">".$val."</option>\n";
    }
}
$select .= "</select>";
echo $select;
?>

Just use array_slice

<?php 
$curr_month = date("m");
$month = array (1=>"January", "February", "March", "April", "May", "June", "July",   "August", "September", "October", "November", "December");
$month = array_slice($month, $curr_month-1);
$select = "<select name=\"month\">\n";
foreach ($month as $key => $val) {
    $select .= "\t<option val=\"".$key."\"";
    if ($key == $curr_month) {
        $select .= " selected=\"selected\">".$val."</option>\n";
    } else {
        $select .= ">".$val."</option>\n";
    }
}
$select .= "</select>";
echo $select;
?>
$remaining = array_slice($month, date('n'));
foreach ($remaining as ...
foreach ($month as $key => $val) {
if ($key >= date('n')){
...

You have an array with 12 elements. So get the current month's "number", subtract one, and start looping up from that spot in your array.

$start_loop_here = date('n')-1;
$thisMonth = date('n');

$month = array (1=>"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$select = "<select name=\"month\">\n";
for ($monthCount = $thisMonth; $monthCount <= 12 ; $monthCount++) {
    $select .= "\t<option val=\"$monthCount\"";
    if ($monthCount == $thisMonth) {
        $select .= " selected=\"selected\">{$month[$monthCount]}</option>\n";
    } else {
        $select .= ">{$month[$monthCount]}</option>\n";
    }
}
$select .= "</select>";
echo $select;

@cenanozen's got a slicker solution. Trim the array down and then iterate over it.

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