Help with PHP and associative arrays
Posted
by errata
on Stack Overflow
See other posts from Stack Overflow
or by errata
Published on 2010-06-02T22:07:25Z
Indexed on
2010/06/02
22:14 UTC
Read the original article
Hit count: 160
Hello.
I have to do a simple calculator in php based on user's input and choice from select field, something like this:
<?php
$a = $_GET['a'];
$b = $_GET['b'];
$array = array( "option1" => 0.1,
"option2" => 0.15,
"option3" => 0.3,
"option4" => 3,
"option5" => 3,
"option6" => 16,
"option7" => 16,
"option8" => 16
);
echo "<form action='calc.php' method='get'>";
echo "<input type='text' name='a' value='".$a."'> of ";
echo "<select name='b'>";
foreach ($array as $k => $v) {
echo "<option value='".$v."'>".$k."</option>";
}
echo "</select> ";
echo "<input type='submit' value='='> ";
$total_volume = $a * $b;
echo $total_volume;
echo "</form>";
?>
Well, for now everything works fine, but the idea is that after user submits form, the page reloads with sent amount in input field and selected option which user actually selected...
First thing is easy: I just put value="a"
in my input field, but I'm not sure how to make a selected option in <select>
field???
I started with this:
foreach ($array as $k => $v) {
echo "<option value='".$v."'";
if ($b == $v) {
echo " selected ";
}
echo ">".$k."</option>";
}
...but this is obviously not working as expected... Please help me with this easy one :)
Thanks!
© Stack Overflow or respective owner