<?
function generateFormField($evt,$data,$name,$width,$emp,$type,$val){
$d = split(',',$data); //split data separated by comma
$c = count($d); //count how many data passed as array after split
sort($d); // sort data like AA, AB
$drop = ''; //initialize the dropdown variable
if($evt):
$evt = " onchange=\"return $evt;\"";
endif;
$drop .= "\n<select name=\"$name\" style=\"width:$width\"$evt>\n"; //dropdown start tag
if($emp==1):
$drop .= "<option value=\"\"></option>\n"; //this empty option will be displayed if $emp=1 from the function properties
endif;
//you don't need to edit the below lines
if($type == 1):
for($i=0; $i<$c; $i++){
if($d[$i]==$_REQUEST[$name] || $d[$i]==$val):
$drop .= "<option value=\"$d[$i]\" selected=\"selected\">$d[$i]</option>\n";
else:
$drop .= "<option value=\"$d[$i]\">$d[$i]</option>\n";
endif;
}
elseif($type == 2):
for($i=0; $i<$c; $i++){
$v = split('=>',$d[$i]);
if($v[1]==$_REQUEST[$name]):
$drop .= "<option value=\"$v[1]\" selected=\"selected\">$v[0]</option>\n";
else:
$drop .= "<option value=\"$v[1]\">$v[0]</option>\n";
endif;
}
endif;
$drop .= "</select>\n";
echo $drop;
}
?>
How to use the function?
<?
/*
$evt = event, incase your dropdown has an event call onChange *optional
$data = is the main values passed to the function to populate the dropdown **required
$name = the name of the dropdown to access its value by your program **required
$width = the width of the box in pixel *optional
$emp = empty, if the value of $emp=1 from the function you will get an empty option in your dropdown, else put 0 **required
$type = data array type (Indexed Array=1 and Associate Array=2) **required
$val = you can postback the selected value to the function. *optional
*/
//examples
generateFormField('eventOnChange(this.value)',"John,Jim",'demo','130px',1,1,$_POST['demo']);//Indexed array
generateFormField('',"Silver=>150,Gold=>300",'package','130px',0,2);//Associate array
?>