Reputation: 40157
I have an array given as:
$my_fontSizes = array("" => "100% Default",
"150%" => "150% of default",
"80%" => "80% of default"
);
When I turn this into a select list, how do I specify that the "value" of the option is what's on the left side of the => sign and the "text label" is what's on the right?
Example, here's what I'm using now, but the element on the right side of the => is being set as both the value and the label:
<select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
<?php foreach ($value['options'] as $option) { ?>
<option<?php if ( get_option( $value['id'] ) == $option) { echo ' selected="selected"'; } ?> value='<?php echo $option; ?>'><?php echo $option; ?></option><?php } ?>
</select>
Upvotes: 1
Views: 634
Reputation: 4206
You would use array_keys() and go through the keys to print the option values.
Upvotes: 0
Reputation: 21353
First, don't mix your PHP and XHTML like that. It's messy and hard to maintain.
Second, note that you're printing $option
as both the name and the value. Here's what I would do:
$my_fontSizes = array(
"" => "100% Default",
"150%" => "150% of default",
"80%" => "80% of default");
$HTML = sprintf('<select name="%s" id="%s">', $Value['id'], $Value['id']);
foreach ($my_fontSizes as $Key => $Value)
{
$Selected = ($OtherValue == $Value) ? 'selected="selected"' : '';
$HTML .= sprintf('<option %s value="%s">%s</option>', $Selected, $Key, $Value);
}
$HTML .= '</select>';
echo $HTML;
Upvotes: 2
Reputation: 77955
<select name="<?=$value['id']?>" id="<?=$value['id']?>">
<?php foreach ($value['options'] as $value=>$option) { ?>
<option<?=(get_option( $value['id'] ) == $value ? ' selected="selected"' : '')?> value='<?=$value?>'><?=$option?></option>
<?php } ?>
</select>
And a slightly more cleaned up markup (but the same answer as everyone else)
Upvotes: 0
Reputation: 2667
Your code is missing a variable named $value and "100% Default" will need a value (like 0 OR null , just to fill the space) but your can loop through your array and get the value and option text like so:
<select>
<?php
foreach($my_fontSizes as $value => $key)
{
?>
<option value="<?php echo $value; ?>"><?php echo $key; ?></option>
<?php
}
?>
</select>
Upvotes: 0
Reputation: 4707
You want to use a slightly different foreach
loop:
foreach($array as $key=>$value)
So your code would be:
<select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
<?php foreach ($value['options'] as $value $option) { ?>
<option<?php if ( get_option( $value['id'] ) == $option) { echo ' selected="selected"'; } ?> value='<?php echo $value; ?>'><?php echo $option; ?></option><?php } ?>
</select>
Upvotes: 1
Reputation: 1693
You want to use a slightly different form of foreach
foreach($array as $key=>$value)
Using this, you are able to grab both the key (left side) and the value (right side) for each option.
Upvotes: 2