开发者

PHP Dropdown Validation

开发者 https://www.devze.com 2023-02-22 01:01 出处:网络
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.

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. 开发者_Python百科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>


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>


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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号