0

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>
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Shawn T
  • 447
  • 6
  • 16
  • @Rizier123 Although [the answer to that question](http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) may lead to the solution for this one, it's by far not a duplicate. – GolezTrol Apr 08 '15 at 18:59
  • @GolezTrol But it's the problem what OP has/run into – Rizier123 Apr 08 '15 at 19:03
  • @Rizier123 And so you can link to that question in a comment, or provide an answer that refers to it. But it's not the same question, so it should not be closed as duplicate. Use your Dupe Hammer wisely. :) – GolezTrol Apr 08 '15 at 19:05

1 Answers1

3

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>"; 
}
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • the answer turns out to be that my error was the single quotes around $list, but your answer helps me even more than just answering. cheers! – Shawn T Apr 08 '15 at 19:36