Given the code below when I select a value from my dropdown box [S, M, L] and hit submit I get one of the following outputs:
S is equal to
M is equal to
L is equal to
I would like the output to be along the lines of
S is equal to Small
M is equal to Medium
L is equal to Large
Can something be added to my code to accomplish this? Or do I need to take a different approach?
<form action="?" method="post">
<?php
$size = array();
$size[] = "";
$size[] = "S";
$size[] = "M";
$size[] = "L";
if(isset($_REQUEST['list'])){
echo $size[(int)$_REQUEST['list']]." is equal to "."<br />";
}
echo '<select name="list">'."\n";
$count = 0;
foreach($size as $size){
echo '<option value="'.$count.'">'.$size.'</option>'."\n";
$count++;
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
<form action="?" method="post">
Why not use an associative array and then you don't have to mess around with ints or $count
s?
<form action="?" method="post">
<?php
$sizes = array(
"S" => "Small",
"M" => "Medium",
"L" => "Large"
);
if(isset($_REQUEST['list'])){
echo "<p>" . $_REQUEST['list'] . " is equal to " . $sizes[$_REQUEST['list']] . "</p>";
}
?>
<select name="list">
<option value="">Choose one</option>
<?php
foreach($sizes as $key => $val){
echo "<option value='$key'>$key - $val</option>\n";
}
?>
</select>
<input type="submit" value="submit" />
</form>
The output will look something like this:
S is equal to Small
+------------+-+
| Choose one |▼|
+------------+-+
| S - Small |
| M - Medium |
| L - Large |
+--------------+
With this solution you can reuse the original static array to populate the post echo. Also try to avoid using \n in your html instead use the semantic <br>
.
<form action="?" method="post">
<?php
$size = array(""=>"","Small"=>"S","Medium"=>"M","Large"=>"L");
if(isset($_REQUEST['list'])){
echo $size[$_REQUEST['list']]." is equal to ".$_REQUEST['list']."<br />";
}
echo "<select name='list'>";
foreach($size as $key=>$value){
echo "<option value='$key'>$value</option>";
}
echo '</select>';
?>
<input type="submit" value="submit" />
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With