Web Development

Creating a Drop Down Selection with an Array

PHP Array – Drop Down Menu

In this section we will show you the basics of making and creating a simple drop down selection array.

First step is to open the php terminal

<?

Next we will call a varible using the word category.

$category

after we set the varible category, you will notice that we use array with an open bracket ( .

= array(

With this array we set each of the components.

(Notice the quotes and the comma after each item).

1=> “Microcyb”,

2=> “Google”,

3=> “YABB”,

4=> “Macromedia”,

5=> “PHP”,

Now we close the array.

);

Next we set the varible category to do a replace string str_replace to make sure any spaces will be populated if added to a database.

$category = str_replace(” “, “ ”, $category);

Next we start the HTML dropdown command, and make sure it has the name equaling the varible.

echo ‘<SELECT name=category>’;

Now we set the loop to do a foreach command to go through the list, and set a value to each in the array.

This will then go through the entire list of items and result in showing the item in a HTML options list.

foreach ($category as $key => $value)

{

echo ‘<OPTION value=’.$value.’> ‘.$value.”;

}

Now, we close the select HTML command.

echo ‘</select>’;

Finally we end the PHP terminal

?>

Full Source Code:

<?

$category = array(

1=> “Microcyb”,

2=> “Google”,

3=> “YABB”,

4=> “Macromedia”,

5=> “PHP”,

);

$category = str_replace(” “, “ ”, $category);

echo ‘<SELECT name=category>’;

foreach ($category as $key => $value)

{

echo ‘<OPTION value=’.$value.’> ‘.$value.”;

}

echo ‘</select>’;

?>

About the author

Written by Darren W..

Darren Hedlund is a freelance Web developer, writer, and data analyst. Darren has a degree in Computer Information Science and has spent the last 15 years developing application and environments from hand held, windows, web, virtual science, gaming, artificial intelligence and graphics design.

Darren's coding knowledge ranges from C+, Visual Basic, .NET, PHP, JSP, REXX, KIXX, and many others. His graphical and environmental knowledge stems in Macromedia Flash, 3D studio Max, Curious Labs Poser, Adobe Photoshop, and many others. Darren works in many platforms ranging from database, visual design, and, system development.

If you found this post useful you may also want to check these out:

  1. How to make your own PHP template script
  2. Creating a Professional Looking Animated Preloader
  3. The PHP Explode Function, Split a String by String
  4. Creating Custom Functions
  5. Flash MX 2004 Layers and Animation Explained
  6. Using HTML Forms With PHP