DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

PHP Select Form Helper

01.24.2008
| 6532 views |
  • submit to reddit
        // takes an array of values and a value to match, and outputs formatted <option>s with the <option> matching $match selected
// must be manually wrapped in <select></select to allow for maximum flexibility

function selectHelper($values, $match)
{
  $keys = array_keys($values);
  $i = 0;
	
  foreach($values as $option)
  {
    $selected = null;
		
    if($match == $keys[$i])
      $selected = " selected";
			
    echo "	<option value=\"".$keys[$i]."\"$selected>".$option."</option>\n";
		
    $i++;
  }
}

//sample usage:
$values = array(
  "lb" => "Pounds",
  "ea" => "Each",
  "oz" => "Ounces");
				
  selectHelper($values, $product->unit);