/ Published in: PHP
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'.
Expand |
Embed | Plain Text
// Number of years to go back $yearRange = 100; // Selected Age $ageLimit = 18; // Generate Options $startYear = ($thisYear - $yearRange); $selectYear = ($thisYear - $ageLimit); $selected = ""; if($year == $selectYear) { $selected = " selected"; } '; }
Comments
Subscribe to comments
You need to login to post a comment.

Sorry dude... your code is wrong.
The correct code is this.
// Number of years to go back $yearRange = 100;
// Selected Age $ageLimit = 18;
// Generate Options $thisYear = date('Y'); $startYear = ($thisYear - $yearRange); $selectYear = ($thisYear - $ageLimit); echo ""; foreach (range($thisYear, $startYear) as $year) { $selected = ""; if($year == $selectYear) { $selected = " selected"; } echo '' . $year . ''; } echo "";
within php tags.
Thanks for this script!
Irish James in Sweden
Damn... I can't post the code properly
ok.. without the < and > then...
// Number of years to go back
$yearRange = 100;
// Selected Age
$ageLimit = 18;
// Generate Options
$thisYear = date('Y');
$startYear = ($thisYear - $yearRange);
$selectYear = ($thisYear - $ageLimit);
echo "select";
foreach (range($thisYear, $startYear) as $year) {
echo "/select";
Sorry for my lack of being able to put the code in properly.
Long live people who share their code...
Oh dear that code was messed up.
with age limit and year starting where the age limit kicks in the code should be:
$thisYear = date('Y');
$selectYear = ($thisYear - $yearRange);
$startYear = ($thisYear - $ageLimit);
echo "select";
foreach (range($selectYear, $startYear) as $year) {
Not sure what is wrong with the original code, other than the missing select tags? It was created to make only the options list itself, not the entire select box (mentioned in the blurb).
I'm just not getting the point of $ageLimit in the code. What if I don't need it what should be that point which I replace within my code. I just need to use it for years no one is entering age there. Please suggest.
Regards
$ageLimit is designed to set the default year that shows up in the select box to a certain number of years ago. So if for example I'm using this for a signup form on a site aimed at over 13 year olds, I can set $ageLimit to 13, and it will automatically work out what the birth year would be for a 13 year old and set it as the default. It was a function required for the original use of this code.
If you want to get rid of it, remove lines 4, 5, 6 & 10, and on line 14 change $selectYear to $thisYear.