Multi select PHP

后端 未结 4 1071
长发绾君心
长发绾君心 2021-01-27 16:04
\" method=\"post\">
提交评论

  • 2021-01-27 16:49

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

    0 讨论(0)
  • 2021-01-27 17:00

    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;
    
    0 讨论(0)
  • 2021-01-27 17:00

    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

    0 讨论(0)
  • 提交回复
    热议问题