Php generate html select options from array

Alec Jacobson

November 08, 2011

weblog/

Here's a super obvious php snippet that generates a list of options for a "select" html form tag on the fly:
<select id="tf_select" name="tf_select"
onchange="update(this,document.getElementById('tf'));">
  <option value="">Select...</option>
  <?php
$a = array("New Haven","Rochester","New York","Washington D.C.","Seattle","Zurich");
foreach($a as $e)
{
  echo "<option value='".$e."'>".$e."</option>";
}
  ?>
  <option value="Other...">Other...</option>
</select>
Combined with the javascript from an earlier post, it should be very easy to generate selectors for php based forms.