I was trying to make a function that calculates the correct answers after a user answers a quiz. The function runs after the user answers all the questions and clicks the Submit button.
The quiz has 10 questions in the DB, but users can only take 5 questions in random order per exam.
The function keeps returning that there is only 1 correct answer even though I answer all 5 questions correctly. I have also performed dd() on all the variables,requests and gets and they show the desired values, So I am assuming that the loop runs once and then breaks, but what could've caused it?
In ExamController:
public function calculateResults(){
// variable that is incremented per correct answer
$totalCorrect = 0;
// array of ids of the questions the user has taken (out of 10 questions in DB, only 5 questions in random order are taken by the user
$takenQuestions = request()->input('taken_questions');
//array of answers provided by user (multiple choice)
$givenAnswers = request()->input('answer');
// get exam id
$exam_id = request()->input('exam_id');
// get all exam questions from DB
$examQuestions = examQuestion::where('exam_id',$exam_id);
// loop through each question that was available in the exam
for($i = 1; $i<=count($takenQuestions);$i++){
// get the question from the exam DB that matches the questions taken by the user
$givenQuestion = $examQuestions->find($takenQuestions[$i]);
//if questions match
if(isset($givenQuestion)){
// get the question's correct answer
$correctAnswer = $givenQuestion->answers->firstWhere('isCorrect',true);
//check if the correct answer and user's given answer matches
if($correctAnswer->content == $givenAnswers[$i]){
//if they match increment correct answer variable
$totalCorrect++;
}
}
}
dd($totalCorrect);
}
I have checked and performed dd() and echo on the following:
-
count($takenQuestions) in the second condition of the for loop returns 5 as desired (So this can't be the cause)
-
$i returns as 1 (as desired) in the first loop and then the echo command doesn't repeat.