Form with a country list statically or dynamically generated

Posted on

Problem

I want to create a form with a country drop down list so I can just google and get all the countries but the question should I just encode it statically or generate dynamically with PHP. (Note it doesn’t have to be necessary country list just any static list with lots of data)

HTML Example:

<select>
  <option value="AF">Afghanistan</option>
  <option value="AX">Åland Islands</option>
  <option value="AL">Albania</option>
  ...
</select>


or use php array i.e.

$countries = array (
    'AF' => 'Afghanistan',
    'AX' => 'Åland Islands',
    'AL' => 'Albania',
    ...
    );

and generate html

<!--Method 1-->
<select>
  <?php foreach($countries as $id => $country) echo "<option value='$id'>$country</option>n" ?>
</select>


Also which method of generating is preferred or is more readable?

<!--Method 2-->
<select>
  <?php foreach($countries as $id => $country):?>
  <option value="<?php echo $id; ?>"><?php echo $country; ?></option>
  <?php endforeach; ?>
</select>

And finally should I escape variables with htmlspecialchars even though I know the output will be valid?

Solution

This depends on your plans for maintaining the software. If it will not be maintained, it does not matter much. If it will be maintained irregularly and manually, not a big issue unless the country code list is used elsewhere, too, e.g. in a database where you store some submitted information or that contains some data per country. But other things being equal, it is better to generate a large dropdown from a table rather than hard-code it. And if the software will be regularly maintained by checking, among other things, the country list and country names against a reliable source, then a table is surely better. It is easier to generate just a table from the reference data.

Note that reliable and useful data can be difficult to find and the set of countries will change (and is subject to political debate). In your example, the second entry does not refer to a country but to an autonomous area. There are definitions of “country codes” that include many non-country entries for various purposes.

Well, it is unlikely for the countries to change much, and even if they do, you might as well change it in HTML rather than in PHP. It really doesn’t matter much, there’s no point in abstracting these.

I’d go with making this static HTML, and save some performance (although probably negligible).


You would want to use PHP however, if you need extra functionality like “Apply selected on the country the user is GeoIP detected from”. That is best handled with PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *