i have this code for select selectbox using Ternory Operator method :
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>
but i output i see all option is selected :
<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>
how do fix this problem?
It's a typo. You are using the assignment operator =
instead of the comparison operator ==
or ===
<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>
Use equivalence operator instead of assignment operator:
<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>
You can either use ==
or ===
while the latter is for strict comparison.