简体   繁体   English

如何在PHP变量中使用if语句?

[英]how can I use an if statement within a php variable?

I am using ajax to call a file on click of a 'card' to display a dialog box. 我使用ajax在单击“卡”以显示对话框时调用文件。 It worked fine as normal html with php but now that I've saved it as a php variable it doesn't like the if statement and the drop downs always show the default 'choose' option. 它与php的普通html一样工作正常,但是现在我将其保存为php变量,它不喜欢if语句,并且下拉菜单始终显示默认的“选择”选项。 Can this be done? 能做到吗? Or maybe I'm just writing it wrong? 也许我只是写错了?

$html.="<select name='priority'>";
$html.="<option>---Choose---</option>";
$html.="<option if ($priority == 'Low') echo 'selected' value='Low'>Low</option>";
$html.="<option if ($priority == 'Normal') echo 'selected' value='Normal'>Normal</option>";
$html.="<option if ($priority == 'High') echo 'selected' value='High'>High</option>";
$html.="<option if ($priority == 'Critical') echo 'selected' value='Critical'>Critical</option>";
$html.="</select>";

It should be done like this: 应该这样完成:

$html .= "<option " .
         (($priority == 'Low') ? 'selected' : '') .
         " value='Low'>Low</option>";

Not using the Ternary operator: 不使用三元运算符:

$html .= "<option ";

if ($priority == 'Low') {
    $html .= 'selected';
}

$html .= " value='Low'>Low</option>";

You probably forget the difference. 您可能会忘记差异。 Everything you have in double quotes is a string. 双引号中的所有内容都是一个字符串。 Try it with ternary: 尝试使用三元:

        $priority = "Normal";
        $html = "";

        //Use from here
        $html .= "<select name='priority'>";
        $html.="<option>---Choose---</option>";
        $html.="<option ";
        $html.= (($priority == 'Low') ? 'selected' : '');
        $html.=" value='Low'>Low</option>";
        $html.="<option ";
        $html.=(($priority == 'Normal') ? 'selected' : '');
        $html.=" value='Normal'>Normal</option>";
        $html.="<option ";
        $html.=(($priority == 'High') ? 'selected' : '');
        $html.=" value='High'>High</option>";
        $html.="<option ";
        $html.=(($priority == 'Critical') ? 'selected' : '');
        $html.=" value='Critical'>Critical</option>";
        $html.="</select>";
        echo $html;
        exit;

Tested! 经过测试!

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

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