开发者

Trying to select an option in a <select> element using PHP

开发者 https://www.devze.com 2023-03-04 20:52 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号