PHP转换为html<;选项>;密码


PHP into html <option...> code

我正在尝试将这个字符串作为php:正常工作

if ($sortvalue == $sort[3]) { echo 'selected=' ;}

转换为此代码:

echo '<select onchange="this.form.submit();" name="sort">
<option value="'.$sort[3].'" HERE_THE_PHP_CODE>Price</option>
[..]
</select>';

我试了很多语法,但总是一页空白。

$selected = '';
if ($sortvalue == $sort[3]) { $selected = 'selected'; }
echo '<select onchange="this.form.submit();" name="sort">
<option value="'.$sort[3].'" $selected>Price</option>
</select>';

这应该是你想要的。(Osama的回复在if语句中有错误)

要保持代码的整洁,应该使用三元运算符。它将允许您在回声中执行if语句。

echo '<select onchange="this.form.submit();" name="sort">
<option value="'.$sort[3].'" ' . ($sort[3] == $sortvalue ? 'selected' : '') . '>Price</option>
[..]
</select>';