linein designs

22 Mar, 2007

Turn 2D Array into a HTML Dropdown with PHP

Posted by: john In: php| programing

Just another quick way to automate the simple process of creating HTML selects with a function. This small function with also remember which value was selected by checking it against the $_POST value and adding a selected="SELECTED" to that option.

2 dimentional array:

$people_array = array(
   '1' => 'Bob',
   '2' => 'James',
   '3' => 'Jessi',
   '4' => 'Sam');

Just call this function either through a request(…) or just simply adding it to the file’s code:

function array2select($array, $post_field){
	foreach($array as $key => $value){
		if($post_field == $key){$selected = ' selected="SELECTED"';}
		echo ''.$value.'';
 		$selected = false;
	}
}

Then just add it where you want the select to do:

< select name="people" >
echo array2select($people_array,$people);
< /select >

This is pretty basic, but it should give you an idea on how arrays and functions can be used together to help speed up projects and automate these basic tasks.

Similar Posts:

No related posts.

Comments »

No comments yet.

Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.

Trackback responses to this post



Please Support Our Sponsors

A Payday advance can be a great way to get back on track.

Banner

About

My name is John Veldboom and have been in design and web programing for just over 8 years now. Started off as a hobby in high school but it has developed into a full time job now. I always tell people that if I wasn't doing this at work each day, I would be at home doing it for free. I love it!

Please visit the contact page to drop me a message.