How to create drop down menu in PHP with example - Biz Tech

How to create drop down menu in PHP with example

Listen

To create a dropdown menu in PHP, you can use HTML and PHP together to generate the HTML code for the dropdown menu.

Here’s an example of how to create a dropdown menu in PHP:


<!DOCTYPE html>
<html>
<head>
	<title>Dropdown Menu Example</title>
</head>
<body>
	<form>
		<select name="fruits">
			<option value="">Select a fruit</option>
			<option value="apple">Apple</option>
			<option value="banana">Banana</option>
			<option value="orange">Orange</option>
			<option value="pear">Pear</option>
		</select>
		<input type="submit" value="Submit">
	</form>
</body>
</html>

In this example, we’ve created a simple HTML form that includes a dropdown menu with four fruit options. The first option in the dropdown menu is a default value that tells the user to select a fruit.

To generate this HTML code dynamically using PHP, you can use a loop to generate the option elements based on an array of fruit names. Here’s an example:

<!DOCTYPE html>
<html>
<head>
	<title>Dropdown Menu Example</title>
</head>
<body>
	<form>
		<select name="fruits">
			<option value="">Select a fruit</option>
			<?php
			$fruits = array("apple", "banana", "orange", "pear");
			foreach ($fruits as $fruit) {
				echo "<option value='" . $fruit . "'>" . ucfirst($fruit) . "</option>";
			}
			?>
		</select>
		<input type="submit" value="Submit">
	</form>
</body>
</html>

In this example, we’ve defined an array of fruit names using the $fruits variable. We then use a foreach loop to generate an option element for each fruit in the array. We use the ucfirst function to capitalize the first letter of each fruit name.

The resulting HTML code will look the same as the first example, but the fruit options will be generated dynamically using PHP.