更改选择(表单)中的选定选项

I have an intial group of options like these:

<select name="item[type]">
    <option value="0" class="dr">First</option>
    <option value="1" class="dr">Second</option>
    <option value="2" class="dr">Third</option>
    <option value="3" class="dr">Fourth</option>
</select>

I want to check if a variable isset($test) is defined. If it is, then I want to change the option selected where the value is equal of $test. Something like this <OPTION SELECTED>

For example. $test = 3; so, the option selected should be fourth. If $test is empty or not defined, then the first should be the option that is selected.

<select name="item[type]" id="selectBoxId">
<option value="0" class="dr">First</option>
<option value="1" class="dr">Second</option>
<option value="2" class="dr">Third</option>
<option value="3" class="dr">Fourth</option>
</select>


<script type="text/javascript">
    var test = "<?= $test; ?>";
    if (test != '' && parseInt(test)) {
        document.getElementById('selectBoxId').selectedIndex = test;
    }
</script>

Remove "[type]" from select name, make it simple to "item". Then execute this code.

$test = isset($_POST['item']) ? $_POST['item'] : "0";

One way:

<select name="item[type]">
    <option <?=$test==0?'selected="selected"':'';?> value="0" class="dr">First</option>
    <option <?=$test==1?'selected="selected"':'';?> value="1" class="dr">Second</option>
    <option <?=$test==2?'selected="selected"':'';?> value="2" class="dr">Third</option>
    <option <?=$test==3?'selected="selected"':'';?> value="3" class="dr">Fourth</option>
</select>

Another:

<? $selected[$test] = 'selected="selected"'; ?>

<select name="item[type]">
    <option <?=$selected[0];?> value="0" class="dr">First</option>
    <option <?=$selected[1];?> value="1" class="dr">Second</option>
    <option <?=$selected[2];?> value="2" class="dr">Third</option>
    <option <?=$selected[3];?> value="3" class="dr">Fourth</option>
</select>
// assuming you are using a loop: in the loop where you create the options
  $selected_html = $test == $loop_var ? ' selected="selected" ' : '';
  echo "<option value=\"$loop_var\" class=\"dr\"$selected_html>$text</option>";