Over a million developers have joined DZone.

Dropdown Select List

·

/**
 * generates html select dropdown list with options
 * if values is two dimensional then adds optgroup too
 * 
 * @param 	string	$name			selectbox name and id
 * @param 	array		$values		options
 * @param 	mixed		$selected	selected option
 * @param 	array		$attributes additonal attributes
 *
 * @return 	string	html source with selectbox
 */
function html_selectbox($name, $values, $selected=NULL, $attributes=array())
{
	$attr_html = '';
	if(is_array($attributes) && !empty($attributes))
	{
		foreach ($attributes as $k=>$v)
		{
			$attr_html .= ' '.$k.'="'.$v.'"';
		}
	}

	$output = '\n";

	return $output;
}




$values = array('animals'=>array(
			1=>'dog', 'cat', 'horse'
		),
		'birds'=>array(
			4=>'gull', 'eagle', 'sparrow')
		);

$selected = isset($_REQUEST['select']) ? $_REQUEST['select'] : 4; // selected item

echo html_selectbox('select', $values, $selected, array('size'=>10));

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}