Home > Software design >  How to foreach defined option start from selected value
How to foreach defined option start from selected value

Time:11-29

On Wordpress (note: this topic is not about Wordpress), first of all, I save a value to the database with a form. Then on another page I get a value from the database and I want to show it as "selected" in the option. I also want to show other options. Actually, (i think) there is a solution for this, but I couldn't find exactly how to search. I will explain briefly with an example. I hope it will be more understandable.

Contents of the file where I saved the values ​​to the database: ...

$countries = array(
    'AF'=>'AFGHANISTAN',
    'AL'=>'ALBANIA',
    'DZ'=>'ALGERIA',
    'AS'=>'AMERICAN SAMOA',
);

//For example, if ALGERIA is selected, save it to the database as DZ.

...

So far everything is fine. Here is the php file with the user profile from which I got the saved data: ...

// Define array again:
$countries = array(
    'AF'=>'AFGHANISTAN',
    'AL'=>'ALBANIA',
    'DZ'=>'ALGERIA',
    'AS'=>'AMERICAN SAMOA',
);
//Get saved data (eg here returns DZ):
$selected_countries = get_user_meta($user_id, $key);

// Show values.
 ?>
<select name="country" id="country">
<?php foreach($countries as $aabrr => $country){ ?>
  <option value="<?php echo $aabrr ?>"> <?php echo $country ?> </option>
<?php } ?>
</select>

...

The problem is that what I want here is to start with the selected value (selected_countries). eg. if DZ is selected the option should start as ALGERIA. Of course, it doesn't make sense to write if for each value separately. There must be a short way around this but I couldn't find it.

CodePudding user response:

Assuming that $selected_country (I used singular here, because the user only selected one country) holds the value DZ:

$countries = array(
    'AF' => 'AFGHANISTAN',
    'AL' => 'ALBANIA',
    'DZ' => 'ALGERIA',
    'AS' => 'AMERICAN SAMOA',
);
$selected_country = get_user_meta($user_id, $key); // DZ
?>
<select name="country" id="country">
<?php foreach($countries as $aabrr => $country){ ?>
  <option value="<?php echo $aabrr ?>"<?php if($aabrr == $selected_country) { echo " selected"; } ?>><?php echo $country ?></option>
<?php } ?>
</select>

The part <?php if($aabrr == $selected_country) { echo " selected"; } ?> will check if the user's selected country (DZ) matches the key part ($aabrr) of the country from the current iteration of your foreach and output selected in the corresponding <option>, which will have it selected.

More on <option>: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

  • Related