If the scores are empty or not numeric, display: “You must enter three valid scores”. The scores are being processed but the message above continues to be displayed. I can’t figure out how to make it stay when needed but go away when valid numbers are entered. Look at the comment “Validate the scores”.
[php]<?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) || !is_numeric($scores)) {
$scores_string = 'You must enter three valid numbers for scores.';
}
break;
// process the scores
/************************************************
* TODO: add code to calculate the score total *
************************************************/
$scores_string = '';
foreach ($scores as $s) {
$scores_string .= $s . '|';
}
} $s = array();
$s[0] = 70;
$s[1] = 80;
$s[2] = 90;
$score_total = array_sum($scores); // Total should be 240
echo $score_total; // Should output 240
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// calculate the average
$score_average = $score_total / count($scores);
// format the total and average
$score_total = number_format($score_total, 2);
$score_average = number_format($score_average, 2);
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;
}
include ‘loop_tester.php’;
?>[/php]