PHP generated year drop down select box

Posted by: Alex on December 9, 2014

A very common feature of forms is the dropdown <select>
box, commonly using a range of years as the options.
Writing and maintaining these long list of options/years can be very monotonous via plain HTML.

This following codebyte generates a simple select box, with an for each year based on some basic arguments.

Change $currently_selected to be the option you want as the top/default option of the select box.
$earliest_year to be the lowest year you want the range to start at.
$latest_year to be the highest year you want your range to go to.

  // Sets the top option to be the current year. (IE. the option that is chosen by default).
  $currently_selected = date('Y'); 
  // Year to start available options at
  $earliest_year = 1950; 
  // Set your latest year you want in the range, in this case we use PHP to just set it to the current year.
  $latest_year = date('Y'); 

  print '&lt;select&gt;';
  // Loops over each int[year] from current year, back to the $earliest_year [1950]
  foreach ( range( $latest_year, $earliest_year ) as $i ) {
    // Prints the option with the next year in range.
    print '&lt;option value="'.$i.'"'.($i === $currently_selected ? ' selected="selected"' : '').'&gt;'.$i.'&lt;/option&gt;';
  print '&lt;/select&gt;';

The above code byte generates: