Kyle Florence Web Designer


Dynamic Select Lists

  • Views624
  • CategoriesPHP
  • Date PublishedFebruary 3, 2006

Using select lists with dynamic content can be tricky, especially when you want the chosen option to remain selected after the user submits the form. In this tutorial, I will cover an easy way to generate select lists based on which option the user selected.

This tutorial will assume basic knowledge of PHP and mySQL. In order to have a dynamic list you must rely on information stored in a database. If you aren't familiar with database storage or queries, please read this tutorial first: Intermediate Templating.

First, you should be familiar with what a select list does, and what it is capable of. The <select> tag is used to create a drop-down listing of options, which are stored in <option> tags within the <select> tags. In this tutorial I am going to use country selection as my example. If you wanted to set up a drop-down menu in which the user can select the country they live in, you may set it up something like this:

<select name="location">
  <option value="">hide</option>
  <option value="Afghanistan">Afghanistan</option>
  <option value="Albania">Albania</option>
  <option value="Algeria">Algeria</option>
  <option value="Zimbabwe">Zimbabwe</option>

You have probably seen this list before. Most websites that store user information use this list that allows users to choose their location without getting false information (such as a country that doesn't exist). Now, if the user selects Albania as their location, we want Albania to appear as their location each time they visit the page that contains this form. That way the user will be able to update other information without having to reselect their location each time. In order for the correct option to be selected, we must look to see what the user entered in the database. That way when we output the data we can add selected="selected" the <option> tag. This will cause that tag to appear selected even if its not the first entry in the list. In order to find the right place to put this, we must have a function that will loop through all of the options in the list outputing the selected option when needed.

function select_list($list_name, $list_value, $list_array) {
    $size = sizeof($list_array);

    $out .= '<select name="'.$list_name.'">';

    for($i = 0; $i < $size; $i++) {
        if($list_array[$i] == 'hide') $out .= '<option value=""';
        else $out .= '<option value="'.$list_array[$i].'"';

        if($list_array[$i] == $list_value) $out .= ' selected="selected"';
        $out .= '>'.$list_array[$i].'</option>';

    $out .= '</select>';
    return $out;

At first glance this may look rather confusing. You're probably wondering how we know all the options in the array, and how we know which one the user selected. Well, since the listing of states is static, we store all the information into an array (which I will show you in a second). Basically, the function takes three parameters: the name of the list itself (which will be the variable the results are stored in), the value you want to check for (user submitted location), and finally our array of options. First we find the size of the array, this is used to loop through the options. Then we begin compiling the list in the variable $out.

While we loop through the results, one of three things happen: we find the value 'hide' (which will leave the users location blank), we don't find a match (which will just output a normal option tag), or we find a match (in which case selected="selected" will be appended to the option tag). After all of this is done, we store the final closing tag into the $out variable (which now contains the entire select list), and then return that to be delt with in whatever way we wish (printed, stored in a variable, whatever).

Below is the array that we will use for this example, which contains all 192 countries (and Taiwan, which is a province of China).

$countries = array('hide', 'Afghanistan', 'Albania', 'Algeria', 'American Samoa', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', 'Antigua & Barbuda', 'Argentina', 'Armenia', 'Aruba', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia', 'Bosnia & Herzegowina', 'Botswana', 'Bouvet Island', 'Brazil', 'British Indian Ocean Territory', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Cayman Islands', 'Central African Republic', 'Chad', 'Chile', 'China', 'Christmas Island', 'Cocos (Keeling) Islands', 'Colombia', 'Comoros', 'Congo', 'Cook Islands', 'Costa Rica', 'Cote D\'Ivoire', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'East Timor', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Falkland Islands (Malvinas)', 'Faroe Islands', 'Fiji', 'Finland', 'France', 'France, Metropolitan', 'French Guiana', 'French Polynesia', 'French Southern Territories', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece', 'Greenland', 'Grenada', 'Guadeloupe', 'Guam', 'Guatemala', 'Guinea', 'Guinea-bissau', 'Guyana', 'Haiti', 'Heard & McDonald Islands', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran, Islamic Republic of', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea, Democratic People\'s Republic of', 'Korea, Republic of', 'Kuwait', 'Kyrgyzstan', 'Lao People\'s Democratic Republic', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libyan Arab Jamahiriya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macau', 'Macedonia, (former) Yugoslav Republic of', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico', 'Micronesia, Federated States of', 'Moldova, Republic of', 'Monaco', 'Mongolia', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'Netherlands Antilles', 'New Caledonia', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk Island', 'Northern Mariana Islands', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Pitcairn', 'Poland', 'Portugal', 'Puerto Rico', 'Qatar', 'Reunion', 'Romania', 'Russian Federation', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent & the Grenadines', 'Samoa', 'San Marino', 'Sao Tome & Principe', 'Saudi Arabia', 'Senegal', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia (Slovak Republic)', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia & South Sandwich Islands', 'Spain', 'Sri Lanka', 'St. Helena', 'St. Pierre & Miquelon', 'Sudan', 'Suriname', 'Svalbard & Jan Mayen Islands', 'Swaziland', 'Sweden', 'Switzerland', 'Syrian Arab Republic', 'Taiwan, Province of China', 'Tajikistan', 'Tanzania, United Republic of', 'Thailand', 'Togo', 'Tokelau', 'Tonga', 'Trinidad & Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Turks & Caicos Islands', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'US, Minor Outlying Islands', 'Uzbekistan', 'Vanuatu', 'Vatican City State (Holy See)', 'Venezuela', 'Viet Nam', 'Virgin Islands (British)', 'Virgin Islands (U.S.)', 'Wallis & Futuna Islands', 'Western Sahara', 'Yemen', 'Yugoslavia', 'Zaire', 'Zambia', 'Zimbabwe');

We can then use this array in our function as the basis of all the options allowed to the user. To find which option the user has selected, we look to our database, where the information was stored on form submission. After we know the value they entered, we can match it to what is in the array, when we find the match, we append the selected="selected" to that option.

$sql = "SELECT * FROM users WHERE id='1' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

$location = select_list('location', $row['location'], $countries);

This should give you a pretty firm understanding of how to use dynamic select lists on your website. Keep in mind that this is only one example of what you can do with this function. In fact, if you want to see a working example of this, check out your "profile" page after you register. See the lists? This is the magic behind how they work.

question? comment? contact me