0

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>
2

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

4 Comments

Woah, a two seconds difference.
did you mean $country instead of $row['country'] in the first bit of code?
@Ben i write $row['country'] bcoz usually we fetch data from database in $row=mysql_fetch_array()
Doesn't make sense in your context
0

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.

1 Comment

interesting mix of , and . :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.