Imagine the following questions
A - What color is red? 1. Red (1 point) 2. Blue (0 points) 3. Green (0 points)
B - How many wheels has a car? 1. Two (0 points) 2. Four (1 point) 3. Nine (0 points)
You show these questions to the user
You may organize an array with the questions and correct answers, like so:
$answers = array(); $answers['a'] = '1'; $answers['b'] = '2';
You will use this to compare later with the submitted answers.
Here is how you can define the name of your input elements so it makes it easier fo verify after submission
If its single answer, it should be radio and the name should be like this
type="radio" name="answers[a]" value="1" type="radio" name="answers[a]" value="2" type="radio" name="answers[a]" value="3"
This upon submission, will appear in the $_POST array like this
$_POST['answers'] = array( 'a' => 'X', 'b' => 'Y', )
Then you can compare the provided answers with the answers you defined in the $answers array
you can do it like this
$user_answers = array(); if ( !empty($_POST['answers']) ) { $user_answers = $_POST['answers']; }
$score = array(); // this will hold the user score. we define it as an array because we will add a new entry per correct answer and use array_sum to calculate the score in the end
foreach ( $user_answers as $question => $answer ) { // the variable $question will have the array key, in this first iteration, it will be 'a' and $answer will have, in this case, 'X' // you can compare like so
$is_answer_correct = $answers[ $question ] === $answer;
// this will verify if in the array $answers, the key $question (in this case is 'a') has the same answer as the user provided.
// the variable $is_answer_correct will be a boolean, either true or false
// if the answer is correct, add one point to the user score
if ( $is_answer_correct === true ) {
$score[] = 1;
}
}
in the end you may get an array like this
$score = array( 1, 0 );
where the user got the first question right and the second one wrong
you will then use array_sum
to calculate the score
$total_score = array_sum($score); // which will return 1