Use PHP to Create Select List

Is there a way to create an HTML Select List with the values of 1900 to 2012?

Or better, from 1900 to the current year?

I believe there is a way to use a PHP loop to do this? :-/

Thanks,

Debbie

Of course there is, but one going up to the current year would probably be more useful.

<?php
$start = 1900;
$end = intval(date('Y'));
echo '<select>';
for($i = $start; $i <= $end; $i++){
    echo "<option>{$i}</option>";
}
echo '</select>';


$res = '<select>';
foreach(range(1999, date('Y')) as $val){
	$res .= "\
<option value='$val'>$val</option>";
}

$res .= "\
</select>";

What do the curly brackets - is that the right name?? - do around the $i ???

Debbie

How about this…


	<!-- Birth Year -->
	<label for="birthYear">Year Born:</label>
	<select id="birthYear" name="birthYear">
		<option value="">--</option>
		<?php
			$currYear = intval(date('Y'));
			$oldestYear = $currYear - 100;

			for($i = $currYear; $i >= $oldestYear; $i--){
				echo '<option value="' . $i . '">' . $i . '</option>';
			}
		?>
	</select>

Debbie

How about this? I think typing the value will usually be quicker than selecting it.


<input name='birthYear' type='number' step='1' placeholder='1970'>

I have no clue what you are doing or what that is?! :eek:

Debbie

He’s suggesting having the user enter 1970, instead of a massive drop down list from which they have to find 1970.

It’s HTML. It’s a number input.
The quickest way to try it would be to select that code, and use Firebug or your browsers developer tools to drop in into the page you’re viewing now.

With a little PHP assistance to limit the range to the last 120 years it’d look like this:


$y = date('Y');
$min = $y-120;

echo "<input name='birthYear' type='number' step='1' value='1970' max='$y' min='$min'>";

(Also decided to change the placeholder attribute to value)

Is that HTML 4???

Step??

Max??

Min??

Placeholder??

Debbie

Just try it out. Unless you’re using IE that will answer most of your questions.
It’s HTML5. In browsers that don’t support this attribute it’ll just act like a normal text box.

Max and min are surely obvious.

Placeholder I decided against, it wasn’t a good use for that attribute, but in browsers that support it, it just gives a suggestion or hint that disappears when the user enters a value.

Step is the increment that the numbers ‘step’ by. Most modern browsers will give a spinner that the user can use as an alternative to typing.

Too much for my brain!!!

I’m sticking with HTML4 for now… :cool:

Thanks anyways,

Debbie

Think of it this way—it’s a text box that users type a year into.
If that user also happens to be using a browser with support (for example Firefox, Chrome, Safari, Opera) the browser will automatically limit them to entering numbers between this year, and 120 years ago.

You still validate server side, just as you have to with a select box.

Okay.

Debbie