tags:

views:

61

answers:

4

I have html-code:

<select name="interest">
    <option value="seo">SEO и Блоговодство</option>
    <option value="auto">Авто</option>
    <option value="business">Бизнес</option>
    <option value="design">Дизайн</option>
    ...

In variable $result['interest'] saved value. How to set element option with value=$result['interest'] in selected? Thanks!

+1  A: 
<select name="interest">
    <option value="seo"<?php if($result['interest'] == 'seo'){ echo ' selected="selected"'; } ?>>SEO</option>
    <option value="auto"<?php if($result['interest'] == 'auto'){ echo ' selected="selected"'; } ?>>Auto</option>
    <option value="business"<?php if($result['interest'] == 'business'){ echo ' selected="selected"'; } ?>>Business</option>
    <option value="design"<?php if($result['interest'] == 'design'){ echo ' selected="selected"'; } ?>>Design</option>
</select>
sshow
+4  A: 
<?php
$interests = array('seo' => 'SEO и Блоговодство',  'auto' => 'Aвто', 'business' => 'Бизнес', ...);
?>
<select name="interest">
<?php
foreach($interests as $k => $v) {
?>
   <option value="<?php echo $k; ?>" <?php if($k == $result['interest']) ?> selected="selected" <?php } ?>><?php echo $v;?></option>
<?php
}
?>
</select>
Jacob Relkin
`+1` neater than my solution
sshow
echoing the html just seems wrong to me
Galen
+2  A: 

The manual way.....

<select name="interest">
    <option value="seo"<?php if($result['interest'] == 'seo'): ?> selected="selected"<?php endif; ?>>SEO и Блоговодство</option>
    .....

The better way would be to loop through the interests

$interests = array(
    'seo' => 'SEO и Блоговодство',
    'auto' => 'Авто',
    ....
);

<select name="interest">
<?php foreach( $interests as $var => $interest ): ?>
<option value="<?php echo $var ?>"<?php if( $var == $result['interest'] ): ?> selected="selected"<?php endif; ?>><?php echo $interest ?></option>
<?php endforeach; ?>
</select>
Galen
A: 
<select name="interest">
<option value="seo" <?php echo $result['interest'] == 'seo' ? 'selected' : ''?> >SEO и Блоговодство</option>
<option value="auto" <?php echo $result['interest'] == 'auto' ? 'selected' : ''?>>Авто</option>
<option value="business" <?php echo $result['interest'] == 'business' ? 'selected' : ''?>>Бизнес</option>
<option value="design" <?php echo $result['interest'] == 'design' ? 'selected' : ''?>>Дизайн</option>
rahim asgari