Populate a HTML Dropdown Box from an Array (or Database) using PHP

Populating a dropdown box given the values of an array, or populating a dropdown box from values in a database is a very easy and useful tool that demonstrates the simplistic power of PHP. Below are a few examples.

In the download below, we’ve included some additional code and a MySQL database dump so you can experiment with the code yourself.

The end result of the below code will give you something that looks like this:


The following code will populate a dropdown box with an option name.
eg: <option value="Sydney">Sydney</option>

<?php
// Array contents
$array1 = array('Sydney','Melbourne','Brisbane','Tasmania','Adelaide','Perth','Darwin','ACT');

// Values from array 1
echo'<select name="cities">';
// For each value of the array assign variable name "city"
foreach($array1 as $city){
    echo'<option value="'.$city.'">'.$city.'</option>';
}
echo'</select>';
?>

The following code will populate a dropdown box with an option value and name.
eg: <option value="s">Sydney</option>

<?
// Array contents
$array2 = array('s'=>'Sydney','m'=>'Melbourne','b'=>'Brisbane','T'=>'Tasmania','a'=>'Adelaide','p'=>'Perth','d'=>'Darwin','t'=>'ACT'); 

// Values from array 2
echo'<select name="cities">';
// For each key of the array assign variable name "cityid"
// For each value of the array assign variable name "city".
foreach($array2 as $cityid=>$city){
    echo'<option value="'.$cityid.'">'.$city.'</option>';
}
echo'</select>';
?>

More often and not, you will want to populate a dropdown box based on the values retrieved from a database. An example .sql dump is attached including a php file in the download below that can be used to test the code.

<?php
// Connect to your database ** EDIT THIS **
mysql_connect("localhost","root",""); // (host, username, password)

// Specify database ** EDIT THIS **
mysql_select_db("dropdown") or die("Unable to select database"); //select db

$result = mysql_query("select DISTINCT id,cities from locations"); 

echo '<select name="city"><OPTION>';
echo "Select an option</OPTION>";
while ($row = mysql_fetch_array($result)){
$id = $row["id"];
$city = $row["cities"];
echo "<OPTION value=\"$id\">$city</OPTION>";
}
echo '</SELECT>';
?>


Download: HTML Dropdown box from PHP array
Description: HTML Dropdown box from PHP array
Author:Marty
Category: PHP code
Date: January 5, 2010

If you liked this article, you may also like:

  1. Generate a Word Cloud from database values or array using PHP
  2. Randomly select rows from a LARGE database with MySQL
  3. Google’s Weather & other Secret API’s
  4. Parse PHP code stored in database
  5. Email Style Priority Field in a Form
About Marty

is a passionate web developer from Sydney, Australia. He owns about 400 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. You can follow Marty on Twitter or Google+.

Speak Your Mind

*