AKor
AKor

Reputation: 8882

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

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?

Upvotes: 2

Views: 198

Answers (2)

xkeshav
xkeshav

Reputation: 54022

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 } ?>

Upvotes: 4

Robert
Robert

Reputation: 1127

http://php.net/manual/en/control-structures.switch.php

The switch statement is similar to a series of IF statements on the same expression.

Upvotes: 0

Related Questions