-1

How can I Populate a Select DropDown with last year value (2016) as selected default?

<?php
 $last_year = date ("Y");
 print "<select>";
 for( $i = 2004; $i <= $last_year; $i++ ) {
  echo "<option selected=\"$last_year\" value=\"$i\">$i</option>\n";
 };
 print "</select>";
?>

Thank you!

BHUVANESH MOHANKUMAR
  • 2,747
  • 1
  • 33
  • 33
Hexman
  • 327
  • 1
  • 11
  • I found similar requirement and solution in below link. http://stackoverflow.com/questions/34206981/php-loop-for-year-dropdown – BHUVANESH MOHANKUMAR Aug 13 '16 at 16:56
  • Sidenote: `echo` uses one less character then `print` (more strain on your fingers). You can see the differences in this Q&A http://stackoverflow.com/questions/1647322/whats-the-difference-between-echo-print-and-print-r-in-php and http://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo - If `print` what you really want to use, the more power to you. – Funk Forty Niner Aug 13 '16 at 17:29

2 Answers2

2
    <?php
    $last_year = date ("Y");
    print "<select>";
    for( $i = 2004; $i <= $last_year; $i++ ) {
        $selected = ($last_year == $i) ? 'selected="selected"' : '';
        echo "<option $selected value=\"$i\">$i</option>\n";
    }
    print "</select>";
    ?>

If I got you right, then this should work for you. What you did was to select every year instead of just the last one.

Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23
1

doing a comparison in the loop like this:

for( $i = 2004; $i <= $last_year; $i++ ) {
    if($i == $last_year){
        $sel = 'selected=selected';
    } else {
        $sel = '';
    }
    echo "<option value='$i' $sel>$i</option>\n";
};
Dave
  • 878
  • 8
  • 19