sw45acp Posted December 13, 2009 Share Posted December 13, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/184996-comparing-and-outputting-two-arrays/ Share on other sites More sharing options...
premiso Posted December 13, 2009 Share Posted December 13, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/184996-comparing-and-outputting-two-arrays/#findComment-976570 Share on other sites More sharing options...
sw45acp Posted December 13, 2009 Author Share Posted December 13, 2009 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; Quote Link to comment https://forums.phpfreaks.com/topic/184996-comparing-and-outputting-two-arrays/#findComment-976573 Share on other sites More sharing options...
premiso Posted December 13, 2009 Share Posted December 13, 2009 Just glad you got it to work with your script, not many people here could have done that so it was my pleasure. Quote Link to comment https://forums.phpfreaks.com/topic/184996-comparing-and-outputting-two-arrays/#findComment-976577 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.