beth
beth

Reputation: 1996

Most efficient way to compare values in an array in PHP

I'd like to use PHP to grade a quiz. I have a quiz that, upon submission, delivers an array of answers. They're all True/False so the array is something like

array([0] => T, [1] => F, [2] => F)

And then I have an answer key, something like

array([0] => T, [1] => F, [2] => T)

I need to go through each answer so I can not only calculate the percentage correct, but also display the correct answers for questions that were missed if and only if the number of missed questions is fewer than 20%.

So my question is, should I be doing some kind of foreach loop to go through each, or would it be tidier to use some kind of array comparison function, and if so, which?

Upvotes: 2

Views: 3144

Answers (3)

flowfree
flowfree

Reputation: 16462

Use foreach():

$answer   = array(true, true, false, true, false);
$expected = array(true, true, true,  true, false);
$error    = array();

foreach ($answer as $k => $v) {
  if ($v !== $expected[$k])
    $error[$k] = $v;
}

// Display the correct answer if number of mistakes is <= 20%
if (floatval(count($error) / count($expected)) <= .2) {
  $correct = array_intersect_key($expected, $error);
}

Upvotes: 3

derabbink
derabbink

Reputation: 2429

Take the grading-array as a starting point. Since it should contain all the keys (for all questions) you can use them to detect missing keys in the submission-array and find all the answers. If you were to calculate the report manually, here's an example:

$submission = array(1 => true, 3 => false, 4 => true, 100 => true);
$grading = array(0 => true, 1 => true, 2 => true, 3 => true, 4 => true);


//gather data
$answered = array();
$missing = array();
$correct = array();
$wrong = array();
foreach ($grading as $key => $answer) {
    if(array_key_exists($key, $submission)) {
        array_push($answered, $key);
        if ($submission[$key] === $answer)
            array_push($correct, $key);
        else
            array_push($wrong, $key);
    }
    else
        array_push($missing, $key);
}


//print report
echo "correct\n";
print_r($correct);
echo "\n\n";

echo "wrong\n";
print_r($wrong);
echo "\n\n";

echo "missing\n";
print_r($missing);
echo "\n\n";

echo "% answered\n";
echo 100*(count($answered)/count($grading));
echo "\n\n";

echo "% correct (of all questions)\n";
echo 100*(count($correct)/count($grading));
echo "\n\n";

echo "% correct (of all answered)\n";
echo 100*(count($correct)/count($answered));
echo "\n\n";

echo "% wrong (of all questions)\n";
echo 100*(count($wrong)/count($grading));
echo "\n\n";

echo "% wrong (of all answered)\n";
echo 100*(count($wrong)/count($answered));

Upvotes: 0

With a foreach loop you will have more control. You can determinate the correct % by dividing the equal values in the array by the total question count.

Upvotes: 0

Related Questions