Reputation: 3168
I am have this query below that is a drop down for year (from 1900-current). I am using a $variable to show a previously chosen year first in the drop down for an edit form. It works except that for all other years 2011 is also repeated with them. How do i tweak it so that $y shows first and then all years underneath that?
Code:
<select name="year">
<?PHP for($i=date("1900"); $i<=date("2011"); $i++)
if($year == $i)
echo "<option value='$y' selected>$y</option>
<option value='$i' selected>$i</option>";
else
echo "<option value='$y' selected>$y</option>
<option value='$i'>$i</option>";
?>
</select></td>
</tr>
Upvotes: 0
Views: 211
Reputation: 14863
Keep it simple:
<select name="year">
<?php for($i=1900; $i<=date('Y'); $i++) {
if($i == date('Y'))
echo "<option value='$i' selected='selected'>$i</option>";
else
echo "<option value='$i'>$i</option>";
}
?>
</select></td>
</tr>
Or even better:
<select name="year">
<?php for($i=1900; $i<=date('Y'); $i++)
echo "<option value='$i' ".(($i == date('Y')?'selected="selected"':'')).">$i</option>";
?>
</select></td>
</tr>
And backwards
<select name="year">
<?php for($i=date('Y'); $i>=1900; $i--)
echo "<option value='$i' ".(($i == date('Y')?'selected="selected"':'')).">$i</option>";
?>
</select></td>
</tr>
Upvotes: 1
Reputation: 17725
Not sure what $y
is, but I guess $year
is the current year:
<select name="year">
<?php
for($i=date("1900"); $i<=date("2011"); $i++)
{
if($year == $i)
echo '<option value="'.$i.'" selected="selected">'.$i.'</option>';
else
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select>
Upvotes: 1
Reputation: 15932
<select name="year">
<?PHP
echo "<option value='$year' selected>$year</option>
for($i=1900; $i<=2011; $i++)
if($year != $i)
echo "<option value='$i'>$i</option>";
<option value='$i'>$i</option>";
?>
</select></td>
</tr>
Upvotes: 1