html select option SELECTED html select option SELECTED php php

html select option SELECTED


Just use the array of options, to see, which option is currently selected.

$options = array( 'one', 'two', 'three' );$output = '';for( $i=0; $i<count($options); $i++ ) {  $output .= '<option '              . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>'              . $options[$i]              . '</option>';}

Sidenote: I would define a value to be some kind of id for each element, else you may run into problems, when two options have the same string representation.


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


This is simple example by using ternary operator to set 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>