Jump to content

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;

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.