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>
";
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>
";
The other suggestions work but for readability I'd prefer:
$selected = ($month == $dbmonth) ? ' selected="selected"' : '';
$monthOptions .= "<option value=\"$month\" $selected >$month</option>
";
There's also less spaghetti code, and eventually you can transition to some sort of template system.