<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 ?
Firstly, $test should be assigned using a ternary operator, that way we can make sure we don't cause PHP Warnings.
Secondly, why even bother using string interpretation of an integer?
Lets make an array that has our answers.
Create a dummy variable we can use to concatenate the values posted.
Now
$t
will be the value of all the posted select items.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
put that IF's into foreach loop
You should make one variable that will contain the result, instead of making price1, price2 and etc.
For example:
You must place the if $t = one , etc. inside the loop