setting a date in a dropdown

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hame22
Forum Contributor
Posts: 214
Joined: Wed May 11, 2005 5:50 am

setting a date in a dropdown

Post by hame22 »

Hi

I have a php page where a user can set a date using 3 html dropdowns, one listing days of the month 01 -31, on listing months, Jan - Dec and one listing the year 1990 -2020

what I want to do is set the selected values in the list the same as the current date. Can this be done to the html components or do I have to recode in php?

Any ideas would be greatly appreicated.

thank you
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

Code: Select all

<?php

function date_drop_down($timestamp = null /* $timestamp = unix timestamp */)
{
	$timestamp = $timestamp ? $timestamp : time();
	for($i = 1; $i < 32; $i++)
	{
		$days[] = $i;
	}
	$days = dropdown($days, date('j', $timestamp));
	
	$months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
	                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
	$months = dropdown($months, date('M', $timestamp));
	
	for($i = 1990; $i < 2020; $i++)
	{
		$years[] = $i;
	}
	$years = dropdown($years, date('Y', $timestamp));
	return '<p><label>Date:</label>'."\n".
	'Day: <select name="day" size="1">'.$days.'</select>'."\n".
	'Month: <select name="month" size="1">'.$months.'</select>'."\n".
	'Year: <select name="year" size="1">'.$years.'</select></p>'."\n";
}

function dropdown($options_array, $selected = null)
{
    $return = null;
    foreach($options_array as $option)
    {
        $return .= '<option value="'.$option.'"'.
                   (($option == $selected) ? ' selected="selected"' : null ).
                   '>'.ucfirst($option).'</option>'."\n";
    }
    return $return;
}

#test it
echo 'Today,'.date_drop_down()."\n";
echo 'Next Friday,'.date_drop_down(strtotime('next friday'))."\n";
echo '+100 days,'.date_drop_down(strtotime('+100 days'))."\n";
echo '+1000 days,'.date_drop_down(strtotime('+1000 days'))."\n";
Post Reply