duanlinjian5819 2018-08-23 18:52
浏览 152

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

This is likely a lot simpler than I'm thinking but I can't seem to figure it out.

I have the following code that's part of a image results list:

<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>

The default of course is 40 results but I want the default to be 80. How do I make it so 80 is automatically selected by default

  • 写回答

1条回答 默认 最新

  • dre93205 2018-08-23 21:21
    关注

    A cleaner way to do this would be:

    <?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>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?