Selected in dynamic select

1

How do I create a selected attribute only in the current year in the <select> that I have below? As we are in 2018, <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>
    
asked by anonymous 07.03.2018 / 00:07

1 answer

2

You can do 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>
    
07.03.2018 / 00:21