Generate a drop-down date picker with PHP; Default to today's date.

This is one of those cases where a little work up-front will save you a ton in the long run.

Rather than typing out a crap-load of <option>item</option> fields, this function will do the following:

Here's a screenshot of the code (cut & paste-able code below):


function dateDropDown($start_year=2008, $default_to_today=true) {
		
		//output month
		$month = "<select id='month'>";
		for($x=1; $x<=12; $x++) {
			$txt = date("M", mktime(0, 0, 0, $x+1, 0, 0, 0));
			$month .= "<option" . ($txt == date("M", time()) && $default_to_today ? ' selected="selected"' : '') . ">" . $txt . "</option>"; 
		} 
		echo $month . "</select>";
		
		//output day
		$day = "<select id='day'>";
		for($x=1; $x<=31; $x++) {
			$txt = date("d", mktime(0, 0, 0, 0, $x, 0, 0));
			$day .= "<option" . ($txt == date("d", time()) && $default_to_today ? ' selected="selected"' : '') . ">" . $txt . "</option>"; 
		}
		echo $day . "</select>";
		
		//output year
		$year = "<select id='year'>";
		for($x=$start_year; $x<=intval(date("Y", time())); $x++) {
			$txt = date("Y", mktime(0, 0, 0, 0, 0, $x+1, 0));
			$year .= "<option" . ($txt == date("Y", time()) && $default_to_today ? ' selected="selected"' : '') . ">" . $txt . "</option>"; 
		}
		echo $year . "</select>";
	}
	
	dateDropDown(2002);