Reputation: 5525
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?
Upvotes: 0
Views: 58
Reputation: 2156
Use as follows,
foreach ( $genders as $key=>$gender ) {
echo '<option value='.$key.' . ( $rowMyBiodata['Gender'] == $gender ? ' selected' : '' ) . '>';
echo $gender;
echo '</option>';
}
Upvotes: 0
Reputation: 28929
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>';
}
Upvotes: 1
Reputation: 8585
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
Upvotes: 1