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>';
?>
If you liked this article, you may also like:

