TSCAmerica.com
TSCAmerica.com

Reputation: 5377

If conditions Multiple - better way - PHP

I have a country dropdown, depending on the database value I would like to show one of the country selected.

The following code works

<?php if ($associate_details["country"]=="AU"){ echo "selected";} ?>

My question is, Is there a better way to show the country selected without writing so many if conditions?

<select style="margin-left:1.5em;" name="associate_country">
<option value="US" >United States of America</option>
<option value="AR">Argentina</option>
<option value="AA">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU" <?php if ($associate_details["country"]=="AU"){ echo "selected";} ?>>Australia</option>

Upvotes: 0

Views: 43

Answers (1)

Kylie
Kylie

Reputation: 11749

You could use some javascript/jquery to set it after the fact

 var country = '<?php echo $associate_details["country"];?>';
 $("select[name='associate_country']").val(country);

JS FIDDLE HERE

But if your countries are stored in an array then you can just do this...

  $countries = [["name"=>"australia","code"=>"AU"], etc etc];

  echo "<select style='margin-left:1.5em;' name='associate_country'>";
  foreach($countries as $value){
   echo "<option value='".$value['code']."' ";
   if ($associate_details["country"]==$value['code']) { echo "selected" ;};
   echo ">".$value['name']."</option>";
  }

Upvotes: 2

Related Questions