I would like to fill a select box with year starting from 1950 to the current year. How can I achieve this using PHP? I would not like to use JavaScript for this.
<select><?php
$currentYear = date('Y');
foreach (range(1950, $currentYear) as $value) {
echo "< option>" . $value . "</option > ";
}
?>
</select>
Use range
to create an array containing all the required years, loop that array and print an option
for each of the values.
You can use date('Y')
to figure out the current year.
// use this to set an option as selected (ie you are pulling existing values out of the database)
$already_selected_value = 1984;
$earliest_year = 1950;
print '<select name="some_field">';
foreach (range(date('Y'), $earliest_year) as $x) {
print '<option value="'.$x.'"'.($x === $already_selected_value ? ' selected="selected"' : '').'>'.$x.'</option>';
}
print '</select>';
Try it here: http://codepad.viper-7.com/Pw3U4O
Documentation
foreach
- http://php.net/manual/en/control-structures.foreach.php
range
- http://php.net/manual/en/function.range.php
date
- http://php.net/manual/en/function.date.php
<select name="select">
<?php
for($i = 1950 ; $i < date('Y'); $i++){
echo "<option>$i</option>";
}
?>
</select>
Something like this?
<?php
$starting_year = 1950;
$ending_year = 2011;
for($starting_year; $starting_year <= $ending_year; $starting_year++) {
$years[] = '<option value="'.$starting_year.'">'.$starting_year.'</option>';
}
?>
<select>
<?php echo implode("\n\r", $years); ?>
</select>
Option #2:
<select>
<?php
foreach(range(1950, (int)date("Y")) as $year) {
echo "\t<option value='".$year."'>".$year."</option>\n\r";
}
?>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With