Populate an HTML select tag with options from an array

Populate an HTML select tag with options from an array

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Populating a Select Tag with Country Codes and Names

Generating a <select> element where the visible text differs from the submitted value is a common requirement in web forms. You often want to display "United States" for readability but submit "US" for database indexing or API validation. The challenge arises when you need to store both pieces of data within your PHP logic without hardcoding them separately, which can lead to duplication errors as your list grows.

Your current approach uses a single array containing only the country names:

$wcr = array(
    'Angola',
    'Antigua & Barbuda',
    'Armenia', 
    // ...
);

And you are iterating through it using each() (which is deprecated in favor of foreach in modern PHP) to assign numeric indices as values. This forces the form to submit "0", "1", "2" instead of the desired ISO codes like "US" or "ES".

To solve this, you must store the code alongside the name. The most robust pattern is an associative array where the key represents the value and the value represents the display text. This structure aligns perfectly with how HTML forms work: the name attribute of the <option> tag determines the submitted value, while the text between the tags is what the user sees.

You can construct this by creating a new array that maps the code directly to the name:

$countries = [
    'US' => 'United States',
    'CA' => 'Canada',
    'GB' => 'United Kingdom',
    // ...
];

When rendering the select box, iterate over this associative array using foreach. Inside the loop, assign $key to the value attribute and $value to the content:

<select name="country">
    <option selected value="">---------</option>
    <?php foreach ($countries as $code => $name): ?>
        <option value="<?php echo htmlspecialchars($code); ?>">
            <?php echo htmlspecialchars($name); ?>
        </option>
    <?php endforeach; ?>
</select>

This approach eliminates the need for asort or numeric indexing entirely. The foreach loop naturally handles the mapping, ensuring that every option submitted corresponds exactly to a key in your array.

Handling Default Selections

A frequent pitfall occurs when you want a country to be pre-selected upon page load. With associative arrays, checking if the default selection matches an existing key is straightforward:

$selected = 'US'; // The ISO code of the currently selected country

foreach ($countries as $code => $name): 
    $isSelected = ($selected === $code) ? 'selected' : '';
?>
    <option value="<?php echo htmlspecialchars($code); ?>" <?php echo $isSelected; ?>>
        <?php echo htmlspecialchars($name); ?>
    </option>
<?php endforeach; ?>

By comparing the $selected variable against the array keys, you ensure that only valid codes can be selected. If a user tries to submit a value not present in the array, the form will either fail validation or ignore it, depending on your backend logic. This is superior to numeric indexing, where "0" might accidentally match a non-existent country if the array isn't strictly ordered.

Where to Get Country Data

While you can manually populate this array for small lists, maintaining ISO codes by hand is prone to typos and version drift. For production applications handling many countries, it is best practice to fetch this data from a standardized source rather than hardcoding it into your PHP files.

If you are working within the Laravel ecosystem, packages like spatie/laravel-country-state-city provide robust, up-to-date lists of countries with their ISO codes directly usable as associative arrays. This ensures your application remains resilient against changes in international standards without requiring manual updates to your codebase. For standalone PHP projects, consider fetching a JSON list from a reliable API or using a static CSV file that you parse into the associative array structure described above.

Security Considerations

When rendering these options, always apply htmlspecialchars() to both the name and the value. Even though ISO codes like "US" are unlikely to contain special characters, user-generated content or future expansions might introduce HTML entities or quotes. Additionally, sanitizing the display text prevents Cross-Site Scripting (XSS) attacks if a country name is ever derived from an external, untrusted source.

By shifting from numeric indices to associative keys, you create a form structure that is both semantically correct and easier to maintain as your data requirements evolve.

Our network