0

I have list of items in my dropdown. Now I wish to select item according to database value. Suppose I have list of cities their are nearly 300 cities. I have city value as new jersey in my record. Now while editing form checking each options is not possible for 300 options. Like

<option value="A" <? if ($a="A") echo "selected"; ?> >A</option>
<option value="B" <? if ($a="B") echo "selected"; ?> >B</option>
<option value="C" <? if ($a="C") echo "selected"; ?> >C</option>
<option value="D" <? if ($a="D") echo "selected"; ?> >D</option>
<option value="E" <? if ($a="E") echo "selected"; ?> >E</option>
<option value="F" <? if ($a="F") echo "selected"; ?> >F</option>
<option value="G" <? if ($a="G") echo "selected"; ?> >G</option>
<option value="H" <? if ($a="H") echo "selected"; ?> >H</option>

Isn't any way to minimise for 300 records. Can't I write short code for this?

** NOTE My options values are not stored in array.**

1
  • 1
    How are you building the options dynamically via a for loop ? Commented Oct 17, 2011 at 15:48

3 Answers 3

4

suppose your values are stored in an array called $options, you could write something like this:

foreach($options as $option)
{
  echo "<option value=\"$option\"";
  if($option == $a)
  {
    echo ' selected="selected"';
  }
  echo ">$option</option>";
}
Sign up to request clarification or add additional context in comments.

2 Comments

@RahulSingh If your values come from a pre-defined range, such as A-Z, then you could replace $options with the range() function mentioned in @GhazanfarMir's answer
if your values do not originate from a range, you could pre-load your options array like this: $options = array('myval1', 'myval2', ...);
0

you should use loops for output

like

$result = mysql_query('select id, city from cities');
while($row = mysql_fetch_assoc($result)) {
    echo '<option value=' . $row['id'] . (($row['city'] == 'new jersey') ? 'selected' : '') . " >" . $row['city'] . '</option>';
}

2 Comments

Why don't you understand my option values are stored in array?
you got nice answer above from hair raisin, use it
0

Try range function in php:

<?php foreach (range('A', 'Z') as $letter){?>
   <option value="<?php echo $letter?>" <? if ($a==$letter) echo "selected='selected'"; ?> ><?php echo $letter?></option>
<?php }?>

Change the range accordingly. You could use this function with integers too.

3 Comments

That means for alphabetical series A-Z first I have to store these values in $letter thinking it as array?
No.. range() function will loop from A-Z storing one letter at a time on each iteration.
but wha would be if I HAVE names in options,, like Ghazanfar,rahul than how will it range/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.