0

I have this code :

$genders = array('Male', 'Female');

foreach ( $genders as $gender ) {
echo '<option' . ( $rowMyBiodata['Gender'] == $gender ? ' selected' : '' ) . '>';
echo $gender;
echo '</option>';
}

and that code produce HTML code like this :

<option selected>Male</option>
<option>Female</option>

now, I want to add a value on each option so that output will be like this :

<option selected value='M'>Male</option>
<option value='F'>Female</option>

I think by changing the array into associative array can solve this problem :

$genders = array('M'=>'Male', 'F'=>'Female');

but how to get array's index so it can be used as value on the option tag?

3 Answers 3

1

Like this:

$genders = array('M' => 'Male', 'F' => 'Female');

foreach ($genders as $key => $value) {
    echo '<option' . ($rowMyBiodata['Gender'] == $value ? ' selected' : '' ) . ' value="' . $key . '">';
    echo $value;
    echo '</option>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

You simply need to change your output script to something like this:

$genders = array('M' => 'Male', 'F' => 'Female');

foreach ( $genders as $gender => $description ) {
    echo '<option value='.$gender.' ' . ( $rowMyBiodata['Gender'] == $description ? ' selected' : '' ) . '>';
    echo $description;
    echo '</option>';
}

Note the new use of the foreach params to have a $key => $value pair, then using this in your output

Comments

0

Use as follows,

foreach ( $genders as $key=>$gender ) {
  echo '<option value='.$key.' . ( $rowMyBiodata['Gender'] == $gender ? ' selected' : '' ) . '>';
  echo $gender;
  echo '</option>';

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.