Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

Populate Dropdown Box from Array (or DB) with PHP

Populating a HTML 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. This was written in 2005. Since then, of course, the MySQL functions are largely unsupported... but we'll keep them for the sake of the examples.

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.
Example: <option value="Sydney">Sydney</option>

1
<?php 
2
/* Array Contents */
3
$array1 = array('Sydney','Melbourne','Brisbane','Tasmania','Adelaide','Perth','Darwin','ACT');
4
 
5
echo '<select name="cities">';
6
 
7
/* For each value of the array assign variable name "city" */
8
foreach($array1 as $city){
9
  echo '<option value="' . $city . '">' . $city . '</option>';
10
}
11
echo'</select>';

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

1
<?php 
2
/* Array contents */
3
$array2 = array('s'=>'Sydney','m'=>'Melbourne','b'=>'Brisbane','T'=>'Tasmania','a'=>'Adelaide','p'=>'Perth','d'=>'Darwin','t'=>'ACT');
4
 
5
echo '<select name="cities">';
6
 
7
foreach($array2 as $cityid => $city) {
8
  echo '<option value="' . $cityid . '">' . $city . '</option>';
9
}
10
echo '</select>';

More often than not, you'll want to populate a dropdown box based on the values retrieved from a database.

1
<?php 
2
$result = mysql_query("select DISTINCT id, cities from locations");
3
 
4
echo '<select name="city"><OPTION>';
5
echo "Select an option</OPTION>";
6
 
7
 while ($row = mysql_fetch_array($result)) {
8
  $id = $row["id"];
9
  $city = $row["cities"];
10
   echo '<OPTION value="' . $id . '">' . $city . '</OPTION>';
11
 }
12
echo '</SELECT>';

It's almost always best to build these features into a function and return the result.

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment