You could also use more complex arrays to both set up the question form and to then check for the answers. Consider if you had this array:
$questions = array(
array(
"question" => "What color is the sky",
"answers" => array(
"red",
"green",
"blue",
"penquine"
),
"correct_answer" => 2
),
array(
"question" => "What is the bestest langugage in the world!",
"answers" => array(
"C#",
"English",
"Brainfuck",
"PHP",
),
"correct_answer" => 3
),
);
In the page where the questions are asked, you could create the form by going through the array and printing each question with it's answers. Somewhat like:
echo "<form action='check_answers.php' method='post'>\n";
foreach ($questions as $qi => $q) {
echo "<h1>{$q["question"]}</h1>\n";
foreach ($q["answers"] as $ai => $answer) {
echo "<label><input type='radio' name='answers[$qi]' value='$ai'> $answer</label>\n";
}
}
echo "<input type='submit'></form>";
The data could then be checked in the check_answers.php file by comparing the "correct_answers" element in each question with the value provided by the form.
if (isset($_POST["answers"]) && is_array($_POST["answers"])) {
$correctAnswers = array();
$incorrectAnswers = array();
foreach ($_POST["answers"] as $question => $answer) {
if ($questions[$question]["correct_answer"] == $answer) {
$correctAnswers[] = $questions;
}
else {
$incorrectAnswers[] = $question;
}
}
echo "You had " . count($correctAnswers) . " correct answers.<br>\n";
echo "You had " . count($incorrectAnswers) . " incorrect answers.<br>\n";
}
You could even extend that to show precicely which questions the user got wrong and which right, as the indexes for both are stored in the arrays.
The $questions array, although being static in the above example, could also easily be generated from a MySQL schema.
function generateQuestions(\PDO $pdo) {
$questions = array();
$sql = "SELECT id, question FROM questions";
$result = $pdo->query($sql);
foreach ($result as $row) {
$question = array(
"question" => $row["question"],
"answers" => array(),
"correct_answer" => 0
);
$answerSql = "SELECT id, answer, isCorrect FROM answers
WHERE question_id = {$row["id"]}";
$answerResult = $pdo->query($answerSql);
foreach ($answerResult as $answer) {
$answers[$answer["id"]] = $answer["answer"];
if ($anser["isCorrect"]) {
$question["correct_answer"] = $answer["id"];
}
}
$questions[$row["id"]] = $question;
}
return $question;
}