Building a dynamic year list for web forms

It’s been a while since I’ve last posted anything on here. Earlier, I was asked by a client to update the year listing on one of the forms on his site. The years were listed in a select statement and was modified manually each year. Yup – epic headache if you ask me. It made more sense to have this dynamically populated with the current year selected and work its way back to a specific year, of course. Otherwise, all hell would break loose and you’d end up with a form that goes as far back as BC.

To avoid the pain and suffering of listing that many years, we’ll cut off our year at, let’s say, 2000… when the modern world should have collapsed after everything was supposed to stop working. Talk about being positive.

The code

<select name="dateYear">
	<?php 
		$date = date("Y");
		echo '<option value="'.$date.'" selected="selected">'.$date.'</option>';
		$i = 1;
		while ($date > "2000") {
			$date = date('Y', strtotime("-".$i." year"));
			echo '<option value="'.$date.'">'.$date.'</option>';
			$i++;
		}
	?>
</select>

And that’s it folks. You’ll never have to revisit that form again. You can also modify this to only go back a certain number of years based on current year so that it automatically keeps your list fresh.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>