Skip to content
PHP Logo

What is the potential issue with the PHP code provided for generating a dropdown list of countries?

The potential issue with the PHP code provided is that it does not handle the selected country properly. To solve this issue, we need to check if each country in the loop matches the selected country and add the 'selected' attribute to the corresponding option tag.

php
// Potential issue: Selected country is not handled in the dropdown list

// Array of countries
$countries = array("USA", "Canada", "UK", "Australia");

// Selected country
$selected_country = "UK";

// Output dropdown list
echo '<select name="country">';
foreach ($countries as $country) {
    if ($country == $selected_country) {
        echo '<option value="' . $country . '" selected>' . $country . '</option>';
    } else {
        echo '<option value="' . $country . '">' . $country . '</option>';
    }
}
echo '</select>';