I have an php array called locArray thats stores an array of locations retrieved from a Database e.g. House 1, House 2 etc. I'm populating a dropdown list with the array and I want the selected index to be the location stored in another table (Person's location) . As it stands the dropdown list selects the first location no matter which location is in the Person's location variable

 <select id="accommodation" name="accommodation" onchange="show()" >
        <?php
        foreach ($locArray as $value) {
        echo'<option value="'.$value.'">'.$value.'</option>'; 
        }
        ?>
    </select>
有帮助吗?

解决方案

Try this:

$select = $client['accommodation'] == $value ? ' selected' : '';
echo '<option value="' . $value . '"' . $select . '>' . $value . '</option>';

其他提示

$currentLoc = $client['accommodation'];

<select id="accommodation" name="accommodation" onchange="show()" >
    <?php
    foreach ($locArray as $value) {
        $selected = '';
        if ($value == $currentLoc) $selected = 'selected';
        echo '<option value="'.$value.'" '.$selected.'>'.$value.'</option>';          
    }
    ?>
</select>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top