开发者

Mantaining dropdown.. Script is so long?

开发者 https://www.devze.com 2023-03-25 03:29 出处:网络
I\'ve read that using session is one way to retain the values from PHP submit failure. The data is wiped out as soon as you send the form to the server so to get back the data, a session should be use

I've read that using session is one way to retain the values from PHP submit failure. The data is wiped out as soon as you send the form to the server so to get back the data, a session should be use. I have a dropdown that is a list of country. It contains more than 60-80 countries. I used the ternary condition to make the script shorter but it's still very long and tiresome.

It looks like this

<option value="Afghanistan" <?php echo (isset($_SESSION["errors"]) && $_SESSION["country"] == "Afghanistan") ? "SELECTED" : ""; ?> >Afghanistan</option>
<option value="Albania" <?php echo (isset($_SESSION["errors"]) && $_SESSION["country"] == "Albania") ? "SELECTED" : ""; ?>>Albania</option>
<option value="Algeria" <?php echo (isset($_SESSION["errors"]) && $_SESSION["country"] == "Algeria") ? "SELECTED" : ""; ?>>Algeria</option>

As 开发者_JS百科I continue this, I thought that there must be another way. Is this a good method? When I see php scripts that is very long, I tend to think that I'm not doing the right way. The list goes on up till now.


Get the list of countries in an array, and loop through it to generate the option tags, for instance:

<?php
// Assuming $countries is an array of country names
foreach ($countries as $country) {
    $selected = (isset($_SESSION['errors']) && $_SESSION['country'] == $country)
        ? 'SELECTED' : '';
    echo "<option value=\"$country\" $selected>$country</option>\n";
}
?>
0

精彩评论

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

关注公众号