Looking for elegant solution to echo 'selected' option

So I have code like this

<select name="s" size="20">
  <option value="402">Audi</option>
  <option value="74">BMW</option>
  <option value="201">Ford</option>
  <option value="35">Saab</option>
  etc etc
</select>

The list goes on and on. I actually have a value for about 1000 models, not just the make.
Anyway to echo that my value is selected, in every single option I paste in the following:

<?php if ($_GET['s'] == '74') { echo 'selected'; } ?>

Then I change the number value in there for each one.

So I end up with a list like this:

<select name="s" size="20">
  <option value="402" <?php if ($_GET['s'] == '402') { echo 'selected'; } ?>>Audi</option>
  <option value="74" <?php if ($_GET['s'] == '74') { echo 'selected'; } ?>>BMW</option>
  <option value="201" <?php if ($_GET['s'] == '201') { echo 'selected'; } ?>>Ford</option>
  <option value="35" <?php if ($_GET['s'] == '35') { echo 'selected'; } ?>>Saab</option>
</select>

This is going to take awhile since I have roughly 1000 models to enter. I’ve done about 30 and I’m sick of it already. Is there a way to elegantly do this so I’m not changing the number value every time? I wouldn’t mind if all I had to paste was a single line of code into every option. It’s much worse to have to go back and change the value for each and every one of them…

Any ideas?

Is this output for each one going to be “selected”?

So, are you storing the key (35) and the make/model (Saab 900) in a database? If not, where are these values coming from?

Why not include an array with your make & model? Then iterate the form?
This is only a suggestion mind you, and my first post.

makemodel.list.php:


<?php
$makemodel = array(1 => 'Audi', 'BMW', 'Ford', 'Saab') ;


?>

Then, use this as your form?


<?php
include 'makemodel.list.php' ;

echo '<select name="s" size="20">' ;

foreach ($makemodel as $i => $value) {
   echo "<option value=\\"$i\\"";
   if ($_REQUEST['s'] == $i)
      {
          echo " selected" ;
      }
   echo ">$makemodel[$i]</option>" ;
}

echo '</select>' ;

?>

Yes, just echo “selected”

No, not in a database. It’s all hard coded.

Thanks, I really like your thinking on this. The only thing is, each model has a specific number to it, so I can’t just run through each sequentially… Would there be a way to add the specific number within the array somehow? Hmmm well now you have me thinking thanks for the suggestion.

You can indeed make the array as you wish!


<?php
$makemodel = array(402 => 'Audi', 74 => 'BMW', 201 => 'Ford', 35 => 'Saab') ; // Keep going down this line,
?>

Yes, exactly! Thanks I think I can now put it all together. Very helpful!