在PHP下拉列表中选择默认选项

时间:2018-08-23 18:52:04

标签: php html html-select

这可能比我想的要简单得多,但我似乎无法弄清楚。

我有以下代码属于图像结果列表:

<option value="30" <?php echo ($_SESSION['results']== 30) ?  'selected' : ''; ?>>30</option>
        <option value="40" <?php echo ($_SESSION['results']== 40) ?  'selected' : ''; ?>>40</option>
        <option value="50" <?php echo ($_SESSION['results']== 50) ?  'selected' : ''; ?>>50</option>
        <option value="60" <?php echo ($_SESSION['results']== 60) ?  'selected' : ''; ?>>60</option>
        <option value="70" <?php echo ($_SESSION['results']== 70) ?  'selected' : ''; ?>>70</option>
        <option value="80" <?php echo ($_SESSION['results']== 80) ?  'selected' : ''; ?>>80</option>
        <option value="90" <?php echo ($_SESSION['results']== 90) ?  'selected' : ''; ?>>90</option>

默认结果为40,但是我希望默认值为80。如何设置默认值80?

1 个答案:

答案 0 :(得分:0)

更干净的方法是:

<?php
session_start();  //Start session

$_SESSION['results'] = $_SESSION['results'] ? $_SESSION['results'] : 80;   //Check and set the session variable else default it to 80

$numbers = [30, 40, 50, 60, 70, 80, 90];   //Initialize your array

?>
<select name="test">
    <?php
    foreach ($numbers as $num) {      //Loop through the array and populate your select box.
        ?>
        <option value="<?php echo $num; ?>" <?php echo ($_SESSION['results'] == $num) ? 'selected' : ''; ?>><?php echo $num; ?></option>
        <?php
    }
    ?>
</select>