I am interested in finding a more efficient way of selecting the proper select option on a select tag with a large amount of options.
The following stripped down example works just fine:
<?php
$favColor = 'blue';
?>
<form>
<label for="favColorSelect">Favorite Color:</label>
<select id="favColorSelect" name="favColorSelect">
<option value="">Select a Color</option>
<option value="red" <?php if($favColor === 'red'){ echo 'selected'; } ?>>Red</option>
<option value="green" <?php if($favColor === 'green'){ echo 'selected'; } ?>>Green</option>
<option value="blue" <?php if($favColor === 'blue'){ echo 'selected'; } ?>>Blue</option>
<select>
</form>
However, if I am listing a large amount of options, such as time zones, adding this code by hand can be tedious. Is there a better way of going about it?
If you can possibly place it in an array/collection you could check with each iteration. Otherwise, what you have is, for all intents and purposes, an adequate way of doing the same.
Tedious maybe, but about typical.
Iteration Method, for reference:
You can shorten your code by the way (assuming you’re allowed to use the short-hand for direct output):