PHP: Drop Down List with Select

by Yang Yang on February 8, 2009

in CSS & HTML Tips, PHP Tips & Tutorials

Populating a drop down list control <select> from a php array is easy, the following function would do it with a breeze. Assuming an array of IT companies:

$companies = array(
	'Microsoft' => 1,
	'Google' => 2,
	'Apple' => 3
);

Feed it as a parameter to the php function below:

function generateSelect($name = '', $options = array()) {
	$html = '<select name="'.$name.'">';
	foreach ($options as $option => $value) {
		$html .= '<option value='.$value.'>'.$option.'</option>';
	}
	$html .= '</select>';
	return $html;
}

with

$html = generateSelect('company', $companies);

you will get an HTML form select control as following:

<select name="company">
	<option value="1">Microsoft</option>
	<option value="2">Google</option>
	<option value="3">Apple</option>
</select>

With data selected from SQL database, you will first convert the SQL results rows to php array and then use it with the generateSelect() function to generate HTML select control drop down list.

Related Posts

{ 5 comments… read them below or add one }

William August 25, 2009 at 11:48 pm

I get that; however, when you use mysql to read the info in the drop-down box, how to mark as selected without hardcoding something directly into html?

Reply

Yang Yang August 29, 2009 at 11:19 pm

You mean, via javascript?

Reply

Sucipto September 18, 2009 at 12:05 am

do you know how to change drop down list value when another drop down list changed?

something like this:
i have 2 drop down list,,
the 1st one is handphone brand
the 2nd one is mobile type..

the 2nd drop down list value depends on the 1st drop down list.
both of the drop down list got the value from mysql DB.

thx

Reply

Walt September 20, 2009 at 12:33 am

I’m not sure how I’m supposed to get the dropdown box. Do I use
$html = generateSelect(‘company’, $companies);
or

Microsoft
Google
Apple

Reply

Walt September 20, 2009 at 12:34 am

Sorry I meant to put in:

select name=”company”>
option value=”1″>MicrosoftGoogleApple</option
/select

Reply

Leave a Comment

Previous post:

Next post: