Selected in dynamic select

Asked

Viewed 193 times

1

How do I create an attribute selected only in the current <select> that I have below? As we are in 2018, the <option> selected should be 2018.

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

1 answer

1


You can do it like this:

<select>
  <?php
    $ano_atual = date("Y");
    for ($i = 2014; $i <= $ano_atual; $i++) {
      $selected = (intval($ano_atual) === $i) ? 'selected' : '';

      echo "<option value=\"$i\" $selected>$i</option>\n";
    }
  ?>
 </select>
  • Show, thank you Brow!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.