0

我很难弄清楚如何获取单选按钮的值以在 switch 语句中使用。基本上,当用户选择其中一个单选按钮时,我希望执行该单选按钮的操作。不确定我是否设置正确。我正在自己学习 PHP,不知道这是否是正确的方法。下面是 HTML 和 PHP。

<input class="radio" type="radio" name="calculate" value="average" checked="checked">Average<br />
<input class="radio" type="radio" name="calculate" value="total">Total<br />
<input class="radio" type="radio" name="calculate" value="both">Both<br />

这是PHP

$calculate_type = $_POST['calculate'];
    switch ($calculate_type) {
        case '$calculate_type == "average"':
            $score_average = $score_total / count($scores);
            break;
        case '$calculate_type == "total"':
            $score_total = $scores[0] + $scores[1] + $scores[2];
            break;
        case '$calculate_type == "both"':
            $score_average = $score_total / count($scores);
            $score_total = $scores[0] + $scores[1] + $scores[2];
            break;
    }
4

1 回答 1

2

你到底在哪里学会写这样的switch陈述???

switch($calculate_type) {
  case "average":
    // do something
    break;
  case "total":
    // do something else
    break;
  case "both":
    // do something completely different
    break;
  default: die("Invalid type");
}

再说一次,在这种情况下,最好如下:

HTML:

<input class="radio" type="radio" name="calculate" value="1" checked="checked">Average<br />
<input class="radio" type="radio" name="calculate" value="2">Total<br />
<input class="radio" type="radio" name="calculate" value="3">Both<br />

PHP:

if( $_POST['calculate'] & 1) $score_average = $score_total / count($scores);
if( $_POST['calculate'] & 2) $score_total = $scores[0]+$scores[1]+$scores[2];
于 2013-10-05T23:12:48.877 回答