PHP选择了Ternary Operator的动态选项

时间:2014-10-21 20:45:12

标签: php ternary-operator

我使用Ternary Operator方法选择选择框的代码:

Ternary operator let us return one of two values based on a given condition. It’s syntax is like below.

(expression)?(if expression is true):(if expression is false)

mycode的:

<select class="form-control contentgroup input-sm" name="access">
<option value="1" <?php echo ($access = 1) ? 'selected' : ''; ?>>1</option>
<option value="2" <?php echo ($access = 2) ? 'selected' : ''; ?>>2</option>
<option value="3" <?php echo ($access = 3) ? 'selected' : ''; ?>>3</option>
</select>

但我输出我看到所有选项都被选中:

<select class="form-control contentgroup input-sm" name="access">
<option value="1" selected>1</option>
<option value="2" selected>2</option>
<option value="3" selected>3</option>
</select>

如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

这是一个错字。您正在使用赋值运算符=而不是比较运算符=====

<option value="1" <?php echo ($access == 1) ? 'selected' : ''; ?>>1</option>
<option value="2" <?php echo ($access == 2) ? 'selected' : ''; ?>>2</option>
<option value="3" <?php echo ($access == 3) ? 'selected' : ''; ?>>3</option>

答案 1 :(得分:0)

使用等价运算符代替赋值运算符:

<option value="1" <?php echo ($access == 1) ? 'selected' : ''; ?>>1</option>
<option value="2" <?php echo ($access == 2) ? 'selected' : ''; ?>>2</option>
<option value="3" <?php echo ($access == 3) ? 'selected' : ''; ?>>3</option>

您可以使用=====,而后者则用于严格比较。