简体   繁体   English

帮助基本的PHP语法

[英]help with basic php syntax

I need some help with php syntax. 我需要有关PHP语法的帮助。 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 .) (假设$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>) 我认为您要使用的是(使用在线条件, (<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. 还有较少的意大利面条代码,最终你可以转换到某种模板系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM