How can PHP code be optimized to efficiently display dropdown menu options from a database query?

To efficiently display dropdown menu options from a database query in PHP, you can optimize the code by fetching the data from the database only once and storing it in an array. Then, loop through the array to generate the dropdown options, reducing the number of database queries and improving performance.

<?php
// Assume $conn is the database connection object

// Fetch data from the database query
$query = "SELECT id, option_name FROM dropdown_options";
$result = $conn->query($query);

// Store the data in an array
$options = array();
while($row = $result->fetch_assoc()) {
    $options[$row['id']] = $row['option_name'];
}

// Generate dropdown menu options
echo '<select name="dropdown">';
foreach($options as $id => $name) {
    echo '<option value="' . $id . '">' . $name . '</option>';
}
echo '</select>';
?>