About Me

My photo
Nadiad, Gujarat, India
Hi Friends I am Vipul Soni, an Innovative web Designer & Developer with Excellent skills who thrives on challenges and is passionate for all areas of web Design & Development.

Wednesday, 2 February 2011

php tricks : create drop down lists

function select_string($array_input,$name,$selected)
$retstring .= "<select name = $name>";
foreach ($array_input as $key => $value)
$retstring .= "<option value = '$key'";
if($selected == $key)
$retstring .= " selected";
$retstring .= ">$value\n";
$retstring .= "</select>\n";
return $retstring;

This function is used to create drop down lists(select option tags) for using in forms.
$array_input is an associative array of all the key/value pairs.
$name has the name you want to give to the <select> tag which will in turn become a variable which will store value of selected option when the form is submitted.
$selected is the value you want as the preselected value in the list.

There advantage of this approach :-

When the form submitted has some errors and needs to be sent back to the user for corrections .. its very easy to recreate select list with the values user filled in the last attempt
eg . $select_list = select_string($array_name,'name',$name);
where 'name' is the name of the variable .. and $name is the value which user submitted in the last attempt ..

Vipul Soni


Post a Comment