How to Post PHP Into a Drop-Down Menu
The HTML "<select>" tag lets you create drop-down menus on a Web page and populate it with items using the "<option value>" tag. However, you cannot use HTML to create drop-down menus with items that may differ from visit to visit. You may use PHP to create a dynamic drop-down menu in your HTML code and then post items from PHP arrays into the menu as its options list. You may create your own array in PHP or get one from elsewhere, such as from user input or an SQL database.
Instructions
-
-
1
Open the HTML file and insert the cursor where you want to display the drop-down menu.
-
2
Type the following to open a PHP tag and create a new PHP array:
<?php
$myArray = array( 'First' => 1, 'Second' => 2, 'Third' => 3, 'Fourth' => 4 );
-
-
3
Type the following to open the drop-down menu's select tag:
echo "<select name=\"dropdownbox\">\n";
Change the name attribute to something that better fits the use of the menu. The "\n" near the end inserts a new line in HTML code, which simply makes the code more readable if somebody views the source code of the page.
-
4
Type the following to create the dynamic drop-down menu using the array:
foreach ($myArray as $arrayItem => $arrayValue) {
echo "\t<option value=\"" . $arrayValue . "\">" . $arrayItem . "</option>\n";
}
The "foreach" function loops through each item in the array, then creates a new option in the drop-down menu. Like the "\n" command, the "\t" makes the code more readable.
-
5
Type the following to close the "select" and PHP tags:
echo "</select>";
?>
-
6
Save the HTML file and upload it to your Web server.
-
1