States of US as PHP array« an older post
a newer one »PHP Curl with XML data

States of US as selected HTML select from array

Snippet

Render an array of USA states as an HTML select / option of USA states, with the current one selected.

/* output directly to screen */
function output_directly($current_state) {
 
  global $states;  // see /snip/states-us-php-array for this array
 
  print "<select name=\"state\">\n";
  print '<option value="" ' . (empty($current_state) ? 'selected="selected"' : '') . ">Select a State</option>\n";
 
  foreach ($states as $abbr => $state) {
    print '<option value="' . $abbr . " " . ($current_state == $abbr ? 'selected="selected"' : '') . '>' . $state . "</option>\n";
  }
 
  print "</select>\n";
}
 
 
/**
 * @param current state
 * @return string of HTML select with states as option
 */
function return_html_string($current_state) { 
 
  // really now, shouldn't $states be a statically defined var?
  global $states;
 
  $c = "<select name=\"state\">\n";
  $c .= '<option value="" ' . (empty($current_state) ? 'selected="selected"' : '') . ">Select a State</option>\n";
 
  foreach ($states as $abbr => $state) {
    $c .= '<option value="' . $abbr . " " . ($current_state == $abbr ? 'selected="selected"' : '') . '>' . $state . "</option>\n";
  }
 
  $c .= "</select>\n";
 
  return $c;
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.