You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML select下拉选项值存在于PHP数组时自动设置selected属性实现方案

解决方案

你注释中预留的判断逻辑只需修正in_array的参数顺序,再把selected属性动态拼接到option标签里即可,修改后的完整代码如下:

$existing_hobby_values = array("Football", "Tennis", "Volleyball");
$sql = "select hobby from hobbies ORDER BY id ASC";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
    echo "<select multiple name='hobbies[]'>";
    while($row = mysqli_fetch_assoc($result)) {
        $interesse = $row['hobby'];
        // 判断当前爱好是否属于用户已选范围,是则添加选中属性
        $selected = in_array($interesse, $existing_hobby_values) ? "selected" : "";
        echo "<option value='$interesse' $selected>$interesse</option>";
    }
    echo "</select>";
}
注意事项
  • 上述代码里已经给select标签补充了name='hobbies[]'属性,多选下拉必须加数组格式的name,否则后端只能接收到最后一个选中的爱好值
  • 如果需要优化安全性,可以对输出的$interesse用htmlspecialchars()转义,避免XSS风险

内容的提问来源于stack exchange,提问作者Bas Schreuder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:57:03