Basically, I have a <select>
element, with a bunch of options. Let's call them A, B, C, D, E.
I'm trying to do this: without a ton of if statements, I want to have the option for the value of $var
(which is either A,B,C,D,E) to be shown by default, regardless of its position in the actual select element.
How could I do that?开发者_Go百科
you can try this way (your options should be in an array)
let
$optionList = array ('A','B','C','D','E','F');
$var = 'D';
then
<select name="mySelect">
<?php foreach($optionList as $k) { ?>
<option value="<?php echo $k;?> <?php if($k === $var )
{ ?> selected="selected" <?php }// end of if ?> >
<?php echo $k;?></option>
<?php } // end of foreach ?>
</select>
EDIT
or you can use if(in_array($var,$optionList)) { ? selected ="selected" <?php } ?>
http://php.net/manual/en/control-structures.switch.php
The switch statement is similar to a series of IF statements on the same expression.
精彩评论