我想填写一个从1950年到今年的年份选择框.如何使用PHP实现这一目标?我不想为此使用JavaScript.
<select><?php
$currentYear = date('Y');
foreach (range(1950, $currentYear) as $value) {
echo "< option>" . $value . "</option > ";
}
?>
</select>
Run Code Online (Sandbox Code Playgroud)
Chr*_*ker 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>';
Run Code Online (Sandbox Code Playgroud)
在这里试试:http://codepad.viper-7.com/Pw3U4O
文档
foreach- http://php.net/manual/en/control-structures.foreach.phprange- http://php.net/manual/en/function.range.phpdate- http://php.net/manual/en/function.date.phpsn0*_*0ep 13
<select name="select">
<?php
for($i = 1950 ; $i < date('Y'); $i++){
echo "<option>$i</option>";
}
?>
</select>
Run Code Online (Sandbox Code Playgroud)
像这样的东西?