Year List Select Box


/ Published in: PHP
Save to your folder(s)

Generates an options list of years for a select box, going from current year backwards through the number of years specified in the first variable.

Useful for birthday fields on signup forms.

eg. 2009, 2008, 2007, 2006 ... 1912, 1911, 1910, 1909

EDITED: Now includes option to set the initially selected value to a set number of years ago. Useful if your form is targetted at a certain age group. Will default to current year if set to '0'.


Copy this code and paste it in your HTML
  1. // Number of years to go back
  2. $yearRange = 100;
  3.  
  4. // Selected Age
  5. $ageLimit = 18;
  6.  
  7. // Generate Options
  8. $thisYear = date('Y');
  9. $startYear = ($thisYear - $yearRange);
  10. $selectYear = ($thisYear - $ageLimit);
  11.  
  12. foreach (range($thisYear, $startYear) as $year) {
  13. $selected = "";
  14. if($year == $selectYear) { $selected = " selected"; }
  15. print '<option' . $selected . '>' . $year . '</option>
  16. ';
  17. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.