Cybervanes - 1 year ago 100

PHP Question

How could I grade this test with php? I need a percentage score...

I have an array of questions containing the correct / incorrect bool and the corresponding weight.

Do I need to find the average of correct answers first?

What would the equation be?

`$questions = array(`

0=>array(

'Question'=>"Some Question",

'Correct'=>true,

'Weight'=>5,

),

1=>array(

'Question'=>"Some Question",

'Correct'=>false,

'Weight'=>5,

),

2=>array(

'Question'=>"Some Question",

'Correct'=>true,

'Weight'=>4,

),

3=>array(

'Question'=>"Some Question",

'Correct'=>true,

'Weight'=>0,

),

4=>array(

'Question'=>"Some Question",

'Correct'=>false,

'Weight'=>5,

),

5=>array(

'Question'=>"Some Question",

'Correct'=>true,

'Weight'=>4,

),

);

$weights = array(

0=>0

1=>0

2=>.05

3=>.20

4=>.25

5=>.50

);

$totalQuestions=0;

$correctAnswers=0;

$points=0;

foreach($questions as $question){

$totalQuestions++;

if($question['Correct']){

$correctAnswers++;

$points = $points = $weights[$question['Weight'];

}

}

Answer Source

You can calculate the amount of weights the candidate earned (i.e. the points you have) and then the total weights possible (i.e. a perfect score).

Then you can divide the candidate score by the total score:

Score = Candidate score / Total Score

From there you can calculate the percentage:

Percentage = Score * 100

Using your code:

```
$totalQuestions=0;
$totalWeights=0;
$correctAnswers=0;
$weightsEarned=0;
foreach($questions as $question){
$totalQuestions++;
$totalWeights+=$weights[$question['Weight']];
if($question['Correct']){
$correctAnswers++;
$weightsEarned += $weights[$question['Weight']];
}
}
echo "Score Overview: ";
echo "<br/>Weights Earned: " . $weightsEarned;
echo "<br/>Correct Answers: " . $correctAnswers;
echo "<br/>Total Weights Possible : " . $totalWeights;
echo "<br/>Percentage Earned: " . ($weightsEarned / $totalWeights) * 100;
```