使用PHP填充使用年份的选择框

时间:2011-08-16 18:27:10

标签: php

我想填写一个从1950年到当年的年份选择框。如何使用PHP实现这一目标?我不想为此使用JavaScript。

<select><?php
     $currentYear = date('Y');
        foreach (range(1950, $currentYear) as $value) {
            echo "< option>" . $value . "</option > ";

        }
?>
</select>

3 个答案:

答案 0 :(得分:23)

使用range创建一个包含所有必需年份的数组,循环该数组并为每个值打印option

您可以使用date('Y')来确定当前年份。

// 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>';

在此处试试:http://codepad.viper-7.com/Pw3U4O

<强>文档

答案 1 :(得分:12)

<select name="select">
<?php 
   for($i = 1950 ; $i < date('Y'); $i++){
      echo "<option>$i</option>";
   }
?>
</select>

这样的东西?

答案 2 :(得分:3)

<?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> 

选项#2:

<select>
<?php

foreach(range(1950, (int)date("Y")) as $year) {
    echo "\t<option value='".$year."'>".$year."</option>\n\r";
}

?>
</select>