Sterica Capatina Sterica Capatina - 3 months ago 4
PHP Question

dynamic selected in select PHP

How can select in dropdown the last year (2016)?



<?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!

Answer
    <?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.

Comments