Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ellajhonm's avatar

My for loop breaks after first loop

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.
0 likes
14 replies
furqanDev's avatar

When you answer question this function runs every time ?

If yes, then the variable $totalCorrect is set to 0 every time. So when you answer the final question it increment it by 1 and return only 1 because you assign it 0 every time you call this function.

ellajhonm's avatar

@furqanDev Sorry, I forgot to mention. No, the function runs after the user answers all the questions and clicks the Submit button.

furqanDev's avatar

@ellajhonm In array of $givenAnswers. Check both the first question and first answer and see if both match.

if($correctAnswer->content == $givenAnswers[$i]){
     $totalCorrect++;
}

Check here whether both content from the table and content provided by the user match.

ellajhonm's avatar

@furqanDev Yes they both match. I checked by doing this:

 echo($correctAnswer->content.' is equal to '.$givenAnswers[$i]);

Output:

E is equal to E

I also checked with the rest of the answers by changing $i to 2,3,4,5. The answers match each other. I don't know why the loop is stopping after $i = 1 :(

furqanDev's avatar

@ellajhonm Your loop is working fine. You can create a variable to test it and increment it. There is something wrong with the logic.

$check = 1;
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				// get the question's correct answer
                  $correctAnswer = $givenQuestion->answers->firstWhere('isCorrect',true);

           if(isset($givenQuestion)){
                    //check if the correct answer and user's given answer matches
                   if($correctAnswer->content == $givenAnswers[$i]){
                       //if they match increment correct answer variable
                       $totalCorrect++;
                   }
           }
		$check++;
        }
dd($check);
ellajhonm's avatar

@furqanDev At first I thought it's probably the if conditions, however when I echo($givenQuestion) (which is before the if conditions) , It only shows one question model. Since this code is inside a for loop, shouldn't it return 5 question models? I wonder why that is?

furqanDev's avatar

@ellajhonm Check the comment

for($i = 1; $i<=count($takenQuestions);$i++){
	// You are finding the exam question with an ID of 1 to 5 in the first loop
	// What if the question that user selected had an ID of 6
	// You are only finding first 5 questions.
	$givenQuestion = $examQuestions->find($takenQuestions[$i]);
}
furqanDev's avatar

@ellajhonm If you are in this case passing an array of id of the question from the form then the loop first part is working fine.

ellajhonm's avatar

@furqanDev I see now ,I also tried echoing $examQuestions->find($takenQuestions[$i] 5 times (outside for loop) and changing the $i variable into 1,2,3,4,5, but it still returns only one record, which means I can't use that syntax for it. What better syntax can I use? I also wonder why I can't use that syntax multiple times to return multiple records?

Tray2's avatar

You are storing the answers in the database right?

Then let the database calculate the correct answers.

ellajhonm's avatar

@Tray2 Oh, I don't. ^^; After getting all the inputs, it goes straight to calculation in the controller. I never thought of storing the answers in the database and calculating from there. If I don't get the first approach to work, I'll change to this one.

Please or to participate in this conversation.