Compoot
Compoot

Reputation: 2387

error in calculating average in php code, output error

I have the following code in php that calculates the average scores. It works, but produces the wrong output (logic error)

Code

<p>Average Score</p>
                <?php
                $avg = 0;
                foreach ($scores as $score) {
                $avg += array_sum($score);
                }
                $avg /= count($scores);
                echo "<tr> <td>$avg</td></tr>"



                ?>

Desired output is 97.5 (because the scores are 100,100,100 and 90) but instead it is displaying: 100.25

UPDATE - scores structure is important

The earlier part of the code generating the scores is as below (to shed some light on the structure of scores -note I don't want an answer that just generates an array and averages it, I can do that, but rather want it fixed in this context)

<?php


                $a = new NewQuizScore;
                $scores = $a->getScores($_SESSION['username']);

                foreach ($scores as $score) {
                    echo ("<tr>");
                    echo ("<td>".$score[0]. "</td> ");
                    echo ("<td>".$score[1]. "</td> ");
                    echo ('<td><a href="certificate.php?name='.$score[0].'&score='.$score[1].'">Print Certificate</a></td>');
                    echo ("<td><a href=\"quiz-show.php?quiz=".$score[2]. "\">Take it again!</a></td> ");
                    echo ("</tr>");
                }



                ?>

Upvotes: 2

Views: 106

Answers (2)

Aman Kumar
Aman Kumar

Reputation: 4547

<?php
$num = [100,100,100,90]; // marks as array 
$avg = array_sum($num) / count($num); // calculate avrage 

echo $avg; // output : 97.5

?>

Update your code as shown below and try

$scoreArr = []; // array for store score

    /* Your output array $scores */
    $scores = [
                [
                "1-Python Basics",
                "100",
                "01_PythonB"
                ],
                [
                "1-Python Output",
                "100",
                "02_Print_O"
                ],
                [
                "1-Python Basics",
                "90",
                "02_Print_O"
                ],
                [
                "1-Python Basics",
                "100",
                "03_Variabl"
                ],
            ];

    foreach($scores as $val) {

        $scoreArr[] = $val[1]; 
    }

    $avg = array_sum($scoreArr) / count($scoreArr); // calculate avrage 

    echo $avg;
    die;

Upvotes: 2

Arun
Arun

Reputation: 3721

Why are you using array_sum?

array_sum() is a function to calculate the sum of values of an array. The value of $score is just a number, right?

Then change the below line

$avg += array_sum($score);

to

$avg += $score;

it will work

Try the below code. It will work in your case

$avg = 0;
foreach($scores as $score){
    $avg += $score[1];
}
$avg /= count($scores);

echo $avg;

Upvotes: 4

Related Questions