简体   繁体   中英

if statement within echo within foreach

I am trying to set selected on an <option> based on an array, and I'm close, but not quite getting there...

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

If I set $found[dept] manually like below, echoing 'selected' works great, but I don't want to write a version of this line for every option.

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

Your variable is in single quotes which makes it a string. It's cleaner and easier to see errors like that if you break out your logic from your output.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM