akrisanov akrisanov - 3 years ago 95
PHP Question

How to set selected value of HTML select box with PHP

I have a next piece of the template:

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

and store resulting value in

How can I mark
element as selected with PHP?


Answer Source

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; ?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download