I need some help with php syntax. How can I add following line
if ($month == $dbmonth) echo ' selected="selected"';
in the following line, inside the option value
$monthOptions .= "<option value=\"$month\" >$month</option>\n";
So that it looks like:
<option value="3" selected="selected" > 3 </option>
(assuming $dbmonth = 3
.)
Thanks for help
echo '<option value="'.$month.'"'
.($month==$dbmonth?' selected="selected':'')
.'>'.$month.'</option>
I think is what you're going for (used an in-line condition, (<condition>?<true outcome>:<false outcome>)
And if this is in a loop:
for ($month = 1; $month < 13; $month++)
echo '<option value="'.$month.'"'
.($month==$dbmonth?' selected="selected':'')
.'>'.$month.'</option>
You could also break it out a little more legibly:
for ($month = 1; $month < 13; $month++)
{
$selected = '';
if ($month == $dbmonth)
$selected = ' selected="selected"';
echo "<option value=\"{$month}\"{$selected}>{$month}</option";
}
You could do something like this.
$monthOptions .= "<option value=\"$month\""
if ($month == $dbmonth) $monthOptions .= ' selected="selected"';
$monthOptions .= ">$month</option>\n";
The other suggestions work but for readability I'd prefer:
$selected = ($month == $dbmonth) ? ' selected="selected"' : '';
$monthOptions .= "<option value=\"$month\" $selected >$month</option>\n";
There's also less spaghetti code, and eventually you can transition to some sort of template system.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.