RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.59%*) • Fixed: 5.39% (6.59%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.48%*) • Investment PI: 5.39% (6.59%*)

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.

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment