Multi select PHP

2020-05-08 23:59发布

<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 ?

4条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-09 00:28

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

查看更多
Rolldiameter
3楼-- · 2020-05-09 00:39

put that IF's into foreach loop

查看更多
Fickle 薄情
4楼-- · 2020-05-09 00:40

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;
查看更多
5楼-- · 2020-05-09 00:55

You must place the if $t = one , etc. inside the loop

查看更多
登录 后发表回答