PHP循环出现额外迭代问题:选择题判分统计结果错误
Hey there, let's figure out why your loop is running one extra time—it's a classic off-by-one error, and totally fixable once we spot the root cause!
The Problem Breakdown
Looking at your form code, you initialize $numberOfLoops = 1, then increment it after processing each question. Let's walk through an example:
- If you have 1 question: you process it, then
$numberOfLoopsbecomes 2 - You pass this value (
2) to the grading page via the hidden inputnumberOfLoops - On the grading side, your loop runs from
$x = 1to$x <= $num(which is 2), so it executes twice instead of once
That's exactly why you're seeing 2 "correct" entries for 1 question—the second iteration tries to access Question2 and actanswer2, which don't exist, skewing your results.
Fixes to Try
Option 1: Adjust the Hidden Input Value in the Form
Instead of passing the incremented $numberOfLoops, pass the actual question count by subtracting 1:
// Replace this line in your form code echo "<input type='hidden' name='numberOfLoops' value='".$numberOfLoops."'>"; // With this: echo "<input type='hidden' name='numberOfLoops' value='".($numberOfLoops - 1)."'>";
Now, if you have 1 question, you pass 1 instead of 2, and the loop runs exactly once.
Option 2: Tweak the Loop Condition in the Grading Script
Keep the form as is, but change the loop to stop before reaching $num:
// Replace this line in grade.php for ($x = 1; $x <= $num; $x++) { // With this: for ($x = 1; $x < $num; $x++) {
Since $num is always one more than the actual question count, this loop will run the correct number of times.
Bonus: A Cleaner Approach to Track Question Count
Initialize $numberOfLoops to 0 instead of 1, and increment it before processing each question. This way, the final value matches the actual number of questions:
// In your form code: $numberOfLoops = 0; foreach ($testArray as $testArray['row']) { $numberOfLoops++; // Rest of your form code using $numberOfLoops } // Now the hidden input can use $numberOfLoops directly echo "<input type='hidden' name='numberOfLoops' value='".$numberOfLoops."'>";
This avoids the off-by-one issue entirely from the start.
内容的提问来源于stack exchange,提问作者user3328625

