如果声明在foreach内回声

时间:2015-04-08 18:52:55

标签: php arrays if-statement foreach

我正在尝试根据数组在selected上设置<option>,我很接近,但还没到达那里......

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

1 个答案:

答案 0 :(得分:3)

您的变量是单引号,使其成为字符串。如果你从输出中突破逻辑,它会更清晰,更容易看到错误。

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

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