Practical Web Programming

Friday, December 05, 2008

PHP: A Simple Function to Create an HTML Select Date Options

Here's a simple PHP function to create a select date options that you can use in your HTML forms to let users select a date. This is simple and easy to use. Below is the function definition.

//RETURN DATE OPTIONS IN HTML
function get_date_options($year = 0000, $month = 00, $day = 00)
{
$ret_val = "";

//ASSEMBLE MONTHS
$options = "<option value='00'>MM</option>";
for ($i = 1; $i < 13; $i++)
{
$attribute = "value='".$i."'";
if ($i == $month)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".str_pad($i,2,0,STR_PAD_LEFT)."</option>";
}
$ret_val .= "<select name='month'>".$options."</select> / ";

//ASSEMBLE DAYS
$options = "<option value='00'>DD</option>";
for ($i = 1; $i < 32; $i++)
{
$attribute = "value='".$i."'";
if ($i == $day)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".str_pad($i,2,0,STR_PAD_LEFT)."</option>";
}
$ret_val .= "<select name='day'>".$options."</select> / ";

//ASSEMBLE YEARS
$options = "<option value='0000'>YYYY</option>";
for ($i = 2008; $i < 2051; $i++)
{
$attribute = "value='".$i."'";
if ($i == $year)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".$i."</option>";
}
$ret_val .= "<select name='year'>".$options."</select>";

return $ret_val;
}


Here's a simple way to use it.

Enter your birthday : <?php print get_date_options() ?>


And here's a way to use it to make default to a date.

Enter your birthday : <?php print get_date_options("2008", "12", "05") ?>

0 comments:

Recent Post