PHP- Code for adding total

I can’t seem to figure out what code to put here to calculate the total. See block comment on line 28. Thanks in advance!

[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 . '|';
    }
}	
    $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]

Hi jaymcgriff,

If you have an array that is filled with numbers, you can get the total by simply using the array_sum() function.

For example,[php]<?php
$scores = array();
$scores[0] = 70;
$scores[1] = 80;
$scores[2] = 90;

$total = array_sum($scores); // Total should be 240
echo $total; // Should output 240[/php]

Let me know if I am misunderstanding what you are looking for.

Best,

jay

Sponsor our Newsletter | Privacy Policy | Terms of Service