html选择选项SELECTED

Jam*_*lle 10 html php selected option

我有我的PHP

$sel = "
    <option> one </option>
    <option> two </option>
    <option> thre </option>
    <option> four </option>
";
Run Code Online (Sandbox Code Playgroud)

假设我有一个内联URL = site.php?sel=one

如果我没有在变量中保存这些选项,我可以这样做,使其中一个选项为SELECTED,其中value等于 $_GET[sel]

<option <?php if($_GET[sel] == 'one') echo"selected"; ?> > one </option>
<option <?php if($_GET[sel] == 'two') echo"selected"; ?> > two </option>
<option <?php if($_GET[sel] == 'three') echo"selected"; ?> > three </option>
<option <?php if($_GET[sel] == 'four') echo"selected"; ?> > four </option>
Run Code Online (Sandbox Code Playgroud)

但问题是,我需要将这些选项保存在变量中,因为我有很多选项,我需要多次调用该变量.

有没有办法让选项在哪里选择value = $_GET[sel]

Sir*_*rko 15

只需使用选项数组,即可查看当前选择的选项.

$options = array( 'one', 'two', 'three' );

$output = '';
for( $i=0; $i<count($options); $i++ ) {
  $output .= '<option ' 
             . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>' 
             . $options[$i] 
             . '</option>';
}
Run Code Online (Sandbox Code Playgroud)

旁注:我将一个值定义为每个元素的某种id,否则当两个选项具有相同的字符串表示时,您可能遇到问题.

  • 更正了.在过去几周内进行了大量的JavaScript编码. (2认同)

Moh*_*hta 6

foreach($array as $value=>$name)
{
    if($value == $_GET['sel'])
    {
         echo "<option selected='selected' value='".$value."'>".$name."</option>";
    }
    else
    {
         echo "<option value='".$value."'>".$name."</option>";
    }
}
Run Code Online (Sandbox Code Playgroud)


Muh*_*had 5

这是使用三元运算符设置 selected=selected 的简单示例

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
  <option value="<?php echo $key;?>" <?php echo ($key ==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
Run Code Online (Sandbox Code Playgroud)