Deepak
Deepak

Reputation: 922

PHP Dropdown Validation

This is the part of an edit page in PHP Here I am displaying the country which is already selected by the user and this code works fine. And in this case there are3 countries only. If I have a lot of countries, then I have to validate with each country and the no: of lines of code will increase. Is there any other option to acheive this?

Select Country: 
<select name="country">
<?php if($country == "india") { ?>
    <option value="">-Select Country-</option>
    <option value="india" selected>india</option>
    <option value="us">us</option>
    <option value="uk">uk</option>
<?php } else if($country == "us"){ ?>
    <option value="">-Select Country-</option>
    <option value="india">india</option>
    <option value="us" selected>us</option>
    <option value="uk">uk</option>
<?php } else{ ?>
    <option value="">-Select Country-</option>
    <option value="india">india</option>
    <option value="us">us</option>
    <option value="uk" selected>uk</option>
<?php } ?>
</select>

Upvotes: 0

Views: 1896

Answers (3)

Sufendy
Sufendy

Reputation: 1242

load the countries into array

$countries = array("india", "us", "uk");

then,

<select name="country">
<?php
  foreach($countries as $c)
  {
     echo "<option ";
     if ($c == $country) echo "selected";
     echo ">$c</option>";
  }
  ?>
</select>

Upvotes: 2

Nican
Nican

Reputation: 7935

Hm, I believe you would be looking for something like this:

<?php

$selected = "india";

$countries = Array(
    ["india"] => "India",
    ["us"] => "United States",
    ["uk"] => "United Kindom",
);

foreach( $countries as $id => $country ){
    echo '<option value="'.$id.'"', $selected == $id ? ' selected' : '' ,'>' . $country . '</option>';
}

?>

Excuse me, I have not coded in PHP in a while, but I believe this is correct.

Upvotes: 0

xkeshav
xkeshav

Reputation: 54016

is this your update county page then do below

first get the selected country from database let

$row['country']='india';

and your country Array is

$countryArray = array ('india','us','uk');

then do below

<select name="country">
<option value="">-Select Country-</option>
<?php foreach( $countryArray as $country) { ?>
<option value="india" <?php if($row['country']===$country ) { ?> selected ="selected" <? } ?><?php echo $country?></option>
<?php } ?>
</select>

Upvotes: 0

Related Questions