I'm creating a simple CRUD app with PHP. On the create page, there's a dropdown menu that allows the user to select what type of highway they're entering info for. On the update page, I'd like the choice that the user made on the create page to be preserved. The value the user chose has been stored in the local JSON object. I came up with the following solution:
<select name="route-type" id="route-type" required>
<option value="" selected="true" disabled>What type of route is this?</option>
<?php if( $highway['type'] == 'interstate') { ?>
<option value="interstate" selected>Interstate</option>
<option value="us-route">US Route</option>
<option value="state-route">State Route</option>
<?php } elseif ( $highway['type'] == 'us-route') { ?>
<option value="interstate">Interstate</option>
<option value="us-route" selected>US Route</option>
<option value="state-route">State Route</option>
<?php } elseif ( $highway['type'] == 'state-route') { ?>
<option value="interstate">Interstate</option>
<option value="us-route">US Route</option>
<option value="state-route" selected>State Route</option>
<?php } ?>
The problem is this seems pretty repetitive and begs to be refactored or rewritten somehow. Any suggestions? Obviously if there were 30 choices in the dropdown it wouldn't be correct to have 30 possible outcomes in the if statement.
here's a solution (untested):
$options = [
'interstate' => 'Interstate',
'use-route' => 'US Route',
'state-route' => 'State Route'
];
foreach($options as $k=>$v) {
echo "<option value=\"$k\"" . ($k===$highway['type']?'selected':'') . " />$v</option>\n";
}