我试图弄清楚如何使用 for 循环来循环遍历数组并测试两个条件。我已经用 foreach 循环完成了它,但试图用 for 循环完成它。下面是我一直在研究的 if 块和 for 循环。
if (empty($scores[0]) ||
empty($scores[1]) ||
empty($scores[2]) ||
!is_numeric($scores[0]) ||
!is_numeric($scores[1]) ||
!is_numeric($scores[2])) {
$scores_string = 'You must enter three valid numbers for scores.';
break;
}
这是HTML和PHP。
HTML:
<form action="." method="post">
<input type="hidden" name="action" value="process_scores" />
<label>Choose action:</label><br />
<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 />
<label>Score 1:</label>
<input type="text" name="scores[]"
value="<?php echo $scores[0]; ?>"/><br />
<label>Score 2:</label>
<input type="text" name="scores[]"
value="<?php echo $scores[1]; ?>"/><br />
<label>Score 3:</label>
<input type="text" name="scores[]"
value="<?php echo $scores[2]; ?>"/><br />
<label> </label>
<input type="submit" value="Process Scores" /><br />
<label>Scores:</label>
<span><?php echo $scores_string; ?></span><br />
<label>Score Total:</label>
<span><?php echo $score_total; ?></span><br />
<label>Average Score:</label>
<span><?php echo $score_average; ?></span><br />
</form>
PHP:
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else {
$action = 'start_app';
}
switch ($action) {
case 'start_app':
$scores = array();
$scores[0] = 70;
$scores[1] = 80;
$scores[2] = 90;
break;
case 'process_scores':
$scores = $_POST['scores'];
// validate the scores
for ($i = 0; $i < count($scores); $i++) {
if (empty($scores[$i]) || !is_numeric($scores[$i])) {
$scores_string = 'You must enter three valid numbers for scores.';
break;
}
}
// process the scores
$scores_string = '';
foreach ($scores as $s) {
$scores_string .= $s . '|';
}
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// Radio buttons
$calculate_type = $_POST['calculate'];
switch ($calculate_type) {
case 'average':
$score_tally = $scores[0] + $scores[1] + $scores[2];
$score_average = $score_tally / count($scores);
$score_average = number_format($score_average, 2);
break;
case 'total':
$score_total = $scores[0] + $scores[1] + $scores[2];
$score_total = number_format($score_total, 2);
break;
case 'both':
$score_tally = $scores[0] + $scores[1] + $scores[2];
$score_average = $score_tally / count($scores);
$score_total = $scores[0] + $scores[1] + $scores[2];
$score_total = number_format($score_total, 2);
$score_average = number_format($score_average, 2);
break;
}
break;
case 'process_rolls':
$number_to_roll = $_POST['number_to_roll'];
$total = 0;
// $count = 0;
$max_rolls = -INF;
for ($count = 0; $count < 1000; $count++) {
$rolls = 1;
while (mt_rand(1, 6) != 6) {
$rolls++;
}
$total += $rolls;
$max_rolls = max($rolls, $max_rolls);
}
$average_rolls = $total / $count;
break;
}
使用此 for 循环验证分数,当存在无效数据时,我不会产生任何结果。