foreach 中的 echo 中的 if 语句

if statement within echo within foreach

我正在尝试在基于数组的 <option> 上设置 selected,我已经接近了,但还没完全实现...

$departments = array("Finance", "IT", "Retail",);

foreach($departments as $list){
    echo '<option';
    if($found['dept'] == '$list'){ // if I set this manually it works, but not now
        echo ' selected';
    }
    echo ' >' . $list . ' </option>'; // this works fine to show me the list
}

如果我像下面那样手动设置 $found[dept],回显 'selected' 效果很好,但我不想为每个选项都写一个版本的这一行。

if($found['dept'] == 'Finance'){ echo 'selected';} > ' .$list . '</option>

您的变量在单引号中,使其成为一个字符串。如果您从输出中分解出您的逻辑,就会更清晰、更容易地看到这样的错误。

$departments = array("Finance", "IT", "Retail",);

foreach($departments as $list){
    $selected  = ($found['dept'] == $list) ? ' selected' : '';
    echo "<option$selected>$list</option>"; 
}