Jump to content

comparing and outputting two arrays


sw45acp

Recommended Posts

I have an array that stores the results of a quiz

$results = array("A","F","B","F","A","T","F");

and an array that has the pre-defined correct results

$correct = array("C","F","B","T","A","T","F");

What I want it to do is output both arrays, and highlight the differences in results in red, like so:

 

1) Chosen Answer: A Correct Answer: C

2) Chosen Answer: F Correct Answer: F

3) Chosen Answer: B Correct Answer: B

4) Chosen Answer: F Correct Answer: T

5) Chosen Answer: A Correct Answer: A

6) Chosen Answer: T Correct Answer: T

7) Chosen Answer: F Correct Answer: F

 

If anybody has any ideas, I thank you muchly.

Link to comment
https://forums.phpfreaks.com/topic/184996-comparing-and-outputting-two-arrays/
Share on other sites

You can simple use a for statement for what you want:

 

$cnt = count($correct);
$output = "";
for ($i=0;$i<$cnt;$i++) {
    $style = ($correct[$i] == $answers[$i]) ? "color: red;" : "";
    $output .= '<span style="$style">' . ($i + 1) . ') Chosen Answer: ' . $answers[$i] . ' Correct Answer: ' . $correct[$i] . '<br />';
}

echo $output;

 

Incase you do not know the ? and : are the ternary operator (which is an if/else statement) near the $style.

Thank you for your help.

I had to change the $answers to $results, and in the <span style="$style"> I changed so that way it could recognize the style. I only wanted incorrect answers in red so I put !== in the turnary operator and added the </span> before the line break. But you did the bulk of it thank you for help!

$results = array("A","F","B","F","A","T","F");
$correct = array("C","F","B","T","A","T","F");
$cnt = count($correct);
$output = "";
for ($i=0;$i<$cnt;$i++) {
    $style = ($correct[$i] !== $results[$i]) ? "color: red;" : "";
    $output .= '<span style="' . $style . '">' . ($i + 1) . ') Chosen Answer: ' . $results[$i] . ' Correct Answer: ' . $correct[$i] . '</span><br />';
}

echo $output;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.