Brian
Brian

Reputation: 37

Create a dropdown menu with range or years automatically

I have a date selector for sorting a calendar.

The "year" option is currently set to show options for: "Current year + 2, with the current year selected"

What I want is actually: "Every year, starting in 2012, with the current year selected and also show the next one year"

I can't sort out the math for the query.

code:

<label for="year">
  <span class="label">Year</span>
    <select name="year">
        <?php
             $year = (isset($_GET['year']) ? $_GET['year'] : date('Y'));

              for ($i=date('Y');$i <= (date('Y')+2);$i++)
              {
                   $checked = ($i == $year ? "selected" : "");

                    echo '<option value="'.$i.'" '.$checked.'>'.$i.'</option>';
               }
         ?>
    </select>
</label>

Upvotes: 0

Views: 748

Answers (1)

lpg
lpg

Reputation: 4937

What about something like this?

<select name="year">
    <?php
         $initialYear = 2012;
         $currentYear = date('Y');

          for ($i=$initialYear;$i <= $currentYear+1 ;$i++)
          {
               $checked = ($i == $currentYear ? "selected" : "");

                echo '<option value="'.$i.'" '.$checked.'>'.$i.'</option>';
           }
     ?>
</select>

Upvotes: 1

Related Questions