How can you optimize the code to avoid repetition when pre-selecting options in a dropdown menu in PHP?
To avoid repetition when pre-selecting options in a dropdown menu in PHP, you can use a loop to iterate through the options and set the "selected" attribute for the option that matches the pre-selected value. This way, you can avoid writing repetitive code for each option.
<select name="dropdown">
<?php
$options = ['Option 1', 'Option 2', 'Option 3'];
$preselected = 'Option 2'; // Set the pre-selected option here
foreach ($options as $option) {
$selected = ($option == $preselected) ? 'selected' : '';
echo "<option value='$option' $selected>$option</option>";
}
?>
</select>
Keywords
Related Questions
- How can the functionality achieved by the "Taschenspieler-Trick" in the code snippet be implemented more effectively using built-in PHP functions?
- When working with multiple XML files in PHP, what are some strategies for efficiently matching and updating data between them based on specific criteria, such as unique identifiers or attribute values?
- What are some common pitfalls to avoid when working with time-dependent calculations in PHP?