Looking for a more elegant way to assign the "selected" attribute to a previously selected <input> element
P粉635509719
P粉635509719 2024-01-16 20:46:55
0
1
416

I'm creating a simple CRUD application using PHP. On the create page, there is a drop-down menu that allows the user to select the type of highway for which they want to enter information. On the update page I want to preserve the selections the user made on the create page. The value selected by the user is stored in a 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 that this looks rather repetitive and needs to be refactored or rewritten in some way. Any suggestions? Obviously, if there are 30 choices in the drop-down list, then it's not correct to have 30 possible outcomes in the if statement.

P粉635509719
P粉635509719

reply all(1)
P粉627136450

Here is 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";
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template