<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<select name="test[]" multiple="multiple">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
<option value="five">five</option>
</select>
<input type="submit" value="Send" />
</form>
<?php
$test=$_POST['test'];
if ($test){
foreach ($test as $t){echo 'You selected ',$t,'<br />';}
}
if($t=='one')
$price1=12;
if($t=='two')
$price2=2;
$total = $price1 + $price2;
echo $total;
When one & two are both selected i'd like the result to be 14. What is the best way to make an addition to obtain 14 as a result ?
You must place the if $t = one , etc. inside the loop
You should make one variable that will contain the result, instead of making price1, price2 and etc.
For example:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<select name="test[]" multiple="multiple">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
<option value="five">five</option>
</select>
<input type="submit" value="Send" />
</form>
<?php
$test = isset($_POST['test']) ? $_POST['test'] : null; // we also want to check if it's set else we'll get an notice
$total = 0;
if ($test) {
foreach ($test as $t) {
echo 'You selected ',$t,'<br />';
switch ($t) {
case "one" : $total += 2; break;
case "two" : $total += 12; break;
}
}
}
echo 'Total: ' .$total;
put that IF's into foreach loop
Firstly, $test should be assigned using a ternary operator, that way we can make sure we don't cause PHP Warnings.
$test = isset($_POST['test']) ? $_POST['test'] : false;
if($test):
//good
endif;
Secondly, why even bother using string interpretation of an integer?
<option value="1">one</option> //note the values
<option value="2">two</option>
Lets make an array that has our answers.
$vals = array(
0 => 'Not an option!',
1 => 12,
2 => 2,
3 => 14,
4 => 26
);
Create a dummy variable we can use to concatenate the values posted.
$val = 0;
foreach($test as $t):
$val += $t;
endforeach;
Now $t
will be the value of all the posted select items.
echo $vals[$val];
And that simple echo statement will supply you with your answer. This way you're not having to do multiple if/else statements, keeps it cleaner and more robust imo.
and here's a Codepad illustrating this