[PHP]Date drop down with today pre-selected

Associate
Joined
21 May 2003
Posts
1,365
Anyone got a regular code snippet they use for this?

There's got to be a more elegant way than the following:
Code:
$nowDate = date("d");
$nowMonth = date("m");
$nowYear = date("Y");

for ($i = 1; $i <= 9; $i++)
{
	if ($nowDate == "0$i")
	{
		echo "<option value='0$i' selected=\"selected\">0$i</option>\n";
	}
	else
	{
		echo "<option value='0$i'>0$i</option>\n";
	}
}

for ($i = 10; $i <= 31; $i++)
{
	if ($nowDate == $i)
	{
		echo "<option value='$i' selected=\"selected\">$i</option>\n";
	}
	else
	{
		echo "<option value='$i'>$i</option>\n";
	}
}

Especially considering it doesn't even take into account how many days in the month...
 
Associate
Joined
21 Oct 2003
Posts
228
I'd replace the code with:

Code:
$nowYear = date("Y");
$nowMonth = date("n");
$nowDate = date("j");
$daysInMonth = date("t");

$outputHTML = "";

for($i=1;$i<=$daysInMonth;$i++)
{
	// select today's date	
	$selection = ($nowDate == $i) ? " selected=\"selected\"" : "";
	
	// zero pad dates less than 10
	$date = ($i<10) ? "0".$i : $i;
	
	$outputHTML.= "<option value=\"$date\"$selection>$date</option>\n";
}
echo $outputHTML;
 
Last edited:
Associate
OP
Joined
21 May 2003
Posts
1,365
Cheers, much more concise.

Thinking about it I don't actually need the $daysInMonth as in this particular situation I need all variants as i'm searching other months too - i'll have to validate the full date once the form is submitted.
 
Back
Top Bottom