Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

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 $result['interest'].

How can I mark option element as selected with PHP?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...