Website Design Company

Ecommerce web site design uk, Custom Web Site Design Company

Dropdown menus using array

This tutorial will explain how to create a dropdown menu using function which populates values from the array. Demo.

To start with create new page and within the body of this page type the following:

<form id="form1" name="form1" method="post" action="">
</form>

Now at the top of the document, before the DOCTYPE, within the php tags create two arrays ­ one for counties and the other one for "how did you hear about us":

<?php

$county = array (′Kent′,′West Susses′,′East Sussex′,′Sommerset′,′Hampshire′,′London′,′Essex′);
$hear = array (′Google′,′Other Search Engine′,′Magazine′,′Recommendation′);

?>

These arrays store values which will be populated to our dropdown menus.
Now we are going to create a function which will take to parameters ­ name of the array and name of the form element. This function will use foreach loop to display all values from the specific array.
After $hear array type:

function createDropdown($arr, $frm) {

echo '<select name="'.$frm.'" id="'.$frm.'"><option value="">Select one…</option>';

foreach ($arr as $key => $value) {

echo '<option value="'.$value.'">'.$value.'</option>';

}

echo '</select>';

}

Now go back to our form and after the line which reads:

<form id="form1" name="form1" method="post" action="">

type:

<label for="frmcounty">County:</label>
<?php createDropdown($county, 'frmcounty'); ?>
<label for="frmhowhear">How did you hear about us?:</label>
<?php createDropdown($hear, 'frmhowhear'); ?>

What′s happened here is we have created labels for the dropdown menus and placed createDropdown() function against them to generate dropdown menus with the values populated from the relevant array. Name of the array is passed via function′s first parameter ($county) and the name of the form element is passed as a second parameter (′frmcounty′).

Save the file and test it in the browser.
This way we can effectively use one function to handle all of the dropdown menus within our form.

Written by Freelance Web Designer - Sebastian Sulinski

Core Media Design is a member of Sussex Enterprise and Federation of Small Businesses

Affordable Web Site Design | Freelance Web Designer | Web Design Tutorials
Web Site Design Sussex | Small Business Web Site Design | Tutorials