Output:
Main Output:
Code:
<?php
session_start();
$questions = [
['question' => 'What is the capital of France?', 'choices' => ['Paris', 'London',
'Berlin', 'Madrid'], 'answer' => 0],
['question' => 'What is 2 + 2?', 'choices' => ['3', '4', '5', '6'], 'answer' => 1],
['question' => 'What is the capital of Japan?', 'choices' => ['Beijing', 'Seoul',
'Tokyo', 'Bangkok'], 'answer' => 2],
['question' => 'What is the largest planet in our solar system?', 'choices' =>
['Earth', 'Mars', 'Jupiter', 'Saturn'], 'answer' => 2],
['question' => 'What is the boiling point of water?', 'choices' => ['90°C',
'100°C', '110°C', '120°C'], 'answer' => 1],
];
function displayQuestion($question, $index) {
echo "<form method='post'><p>" . ($index + 1) . ". " . $question['question'] .
"</p>";
foreach ($question['choices'] as $choiceIndex => $choice) {
$checked = isset($_SESSION['answers'][$index]) &&
$_SESSION['answers'][$index] == $choiceIndex ? 'checked' : '';
echo "<input type='radio' name='answer_$index' value='$choiceIndex'
$checked> $choice<br>";
}
echo "<input type='submit' name='submit_$index' value='Next'></form>";
}
function calculateScore($questions) {
$score = 0;
foreach ($questions as $index => $question) {
if (isset($_SESSION['answers'][$index]) && $_SESSION['answers'][$index]
== $question['answer']) {
$score++;
}
}
return $score;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($questions as $index => $question) {
if (isset($_POST["submit_$index"])) {
if (isset($_POST["answer_$index"])) {
$_SESSION['answers'][$index] = $_POST["answer_$index"];
}
$nextQuestion = $index + 1;
if ($nextQuestion < count($questions)) {
header("Location: ?q=$nextQuestion");
} else {
echo "<p>Your score is: " . calculateScore($questions) . "</p>";
echo "<form method='post'><input type='submit' name='try_again'
value='Try Again'></form>";
session_destroy();
}
exit;
}
}
}
if (isset($_POST['try_again'])) {
session_destroy();
header("Location: ?q=0");
exit;
}
$currentQuestion = isset($_GET['q']) ? (int)$_GET['q'] : 0;
if ($currentQuestion < count($questions)) {
displayQuestion($questions[$currentQuestion], $currentQuestion);
}
?>