我在下面有一个下拉菜单:
$form = "
<form action='" . htmlentities($_SERVER["PHP_SELF"]) . "' method='post'>
<table>
<tr>
<td><select name='year' id='yearDrop'>
<option value=''></option>
<option value='$getyear[1]'>1</option>
<option value='$getyear[2]'>2</option>
<option value='$getyear[3]'>3</option>
<option value='$getyear[4]'>4</option>
<option value='$getyear[5]'>5</option>
<option value='$getyear[6]'>6</option>
<option value='$getyear[7]'>7</option>
<option value='$getyear[8]'>8</option>
<option value='$getyear[9]'>9</option>
<option value='$getyear[10]'>10</option>
</select></td>
</tr>
</table>
</form>
";
请注意,下拉菜单位于表单中的 php 变量中。我的问题是:“有没有更好更短的方法来显示上面的下拉菜单?”。也许通过使用某种循环来遍历每个值并为每个选项赋予相同的value
属性?
我想使用getyear
以适应一个简单的 if 语句:
if ($getyear){
echo "year is chosen";
}else{
$errormsg = "You must enter in Student's current Academic Year to Register";
}
更新:
<?php
$getyear = (isset($_POST['year'])) ? $_POST['year'] : '';
$errormsg = (isset($errormsg)) ? $errormsg : '';
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$yearHTML = '';
$yearHTML .= '<select name="year" id="yearDrop">'.PHP_EOL;
$yearHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($years as $year) {
$yearHTML .= "<option>$year</option>".PHP_EOL; // if no value attribute, value will be whatever is inside option tag, in this case, $year
}
$yearHTML .= '</select>';
if( (isset($_POST['registerbtn']))){
$getyear = $_POST['year'];
if (!in_array($getyear , $years)){
echo "year is chosen";
}else{
$errormsg = "You must enter in Student's current Academic Year to Register";
}
}
$form = "
<form action='" . htmlentities($_SERVER["PHP_SELF"]) . "' method='post'>
<table>
<tr>
<td></td>
<td id='errormsg'>$errormsg</td>
</tr>
<tr>
<td>Year:</td>
<td>{$yearHTML}</td>
<td><input type='text' name='year' value='$getyear' /></td>
</tr>
<tr>
<td></td>
<td><input type='submit' value='Register' name='registerbtn' /></td>
</tr>
</table>
</form>";
echo $form;
?>