-1

How can I get a percentage of right answers if I have 2 arrays in PHP or javascript, preferably in PHP?

So, I have these two arrays and I want to compare a quiz result with the correct answers and get a percentage score:

$quiz_results = array( 'q1' => 'no',
                    'q2' => 'yes',
                    'q3' => 'no',
)

$answers = array( 1 => 'yes',
                  2 => 'no',
                  3 => 'yes'
)
allicarn
  • 2,859
  • 2
  • 28
  • 47
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
  • Why not loop over the question array and add a point for every correct answer? – feeela Sep 23 '15 at 13:54
  • Set the keys to the same value and simply check if $answers[1] == $quiz_results[1]. After that get the total amount of questions compared to the correct amount – Crecket Sep 23 '15 at 13:54

2 Answers2

3

Run through the answers and compare them to the questions. If they are the same increment the correct answer count.

$quiz_results = array( 'q1' => 'yes',
                    'q2' => 'yes',
                    'q3' => 'no',
);
$answers = array( 1 => 'yes',
                  2 => 'no',
                  3 => 'yes'
);

$totalquestions = count($answers);
$correct = 0;
foreach($answers as $key => $answer){
    //q + the key should do it. Its easier if they are the same obviously
    if($answer == $quiz_results['q'.$key]){
        // correct 
        $correct++;
    }
}

echo 100 / $totalquestions * $correct; //returns 33.333333%
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Crecket
  • 718
  • 2
  • 7
  • 24
1

A slightly different approach to the problem

$rating=array_merge(
    array_fill_keys( range(0,32), 'Poor' ),
    array_fill_keys( range(33,65), 'Moderate' ),
    array_fill_keys( range(66,89), 'Above average' ),
    array_fill_keys( range(90,100), 'Excellent' )
);
$quiz_results = array(
    'q1' => 'no',
    'q2' => 'yes',
    'q3' => 'no'
);
$answers = array(
    1 => 'yes',
    2 => 'no',
    3 => 'yes'
);

$i=1;
$score=0;

while( $answer = current( $quiz_results ) ) {
    $score += ( $answer==$answers[ $i ] ) ? 1 : 0;
    echo 'Question [ '.$i.' ]: You answered: '.$answer.', The correct answer is: '.$answers[ $i ].'<br />';
    $i++;
    next( $quiz_results );
}
echo 'Score: '.$score.'/'.count( $quiz_results ).' - '.round( abs( ( $score / count( $quiz_results ) ) * 100 ),2).'%';
echo '<br />Rating: '. $rating[ ceil( abs( ( $score / count( $quiz_results ) ) * 100 ) ) ];

Will output:

You answered: no, The correct answer is: yes
You answered: yes, The correct answer is: no
You answered: no, The correct answer is: yes
Score: 0/3 - 0%
Rating: Poor
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46