Hans Pede Hans Pede - 5 months ago 15
SQL Question

Drop down - show previously selected in loop

my problem is to show previously selected in a while loop. I found a way to do it in not-loop setup, but a loop is a problem for me.

The following code give me a drop down of countries (and country code):

<?php

foreach($countries as $key => $value) { ?>

<option value="<?= $value . ' ' . $key ?>" title="<?= htmlspecialchars($value) ?>"><?= htmlspecialchars($value) ?></option>

<?php } ?>


And it works good. But imagine someone edit their country, thus I would love to show previously selected country. Of course I have a variable with the specific previously selected country... Thanks.

Answer
<?php 
$preselected = 'whatever_previous_selected';

foreach($countries as $key => $value) { ?>

<option value="<?php $value; ?>" title="<?= htmlspecialchars($value) ?>" <?php if($preselected == $value) {echo "selected='selected'"; }?>>
<?= htmlspecialchars($value) ?>
</option>

<?php } ?>
Comments