How can PHP code be optimized to prevent concatenating IDs in a dropdown menu?
When populating a dropdown menu with dynamic IDs in PHP, it is not efficient to concatenate IDs in the HTML output loop. Instead, you can use an associative array to store the IDs and corresponding values, then loop through the array to generate the dropdown options. This approach separates the data from the presentation, making the code cleaner and easier to maintain.
<?php
// Sample data for dropdown menu
$options = [
1 => 'Option 1',
2 => 'Option 2',
3 => 'Option 3',
];
// Generate dropdown menu
echo '<select>';
foreach ($options as $id => $value) {
echo "<option value='$id'>$value</option>";
}
echo '</select>';
?>