For a multiple choice exam, i store the data in .txt
files.
I have 8 .txt
files in which stored 2 or more numbers. The name of the txt files are 1.txt, 2.txt, 3.txt ...
The first number in each txt file is ALWAYS the correct answer. I want to compare this first number with the last number of that txt file.
foreach($all_files as $file) {
$each_file = file_get_contents($file);
$choosen_answer = substr($each_file, -1); // last number is the number user has choosen
$correct_answer = substr($each_file, 0,1); // first number is the correct answer
// output the answers
echo '<span class="choosen_answer">'.$choosen_answer.'</span>';
echo '<span class="correct_answer">'.$correct_answer.'</span>';
$wrong = 0;
if($choosen_answer != $correct_answer) { // compare the 2 values
$wrong++;
echo '<span class="wrong text-danger">Wrong</span>';
}
else {
echo '<span class="correct text-success">Correct</span>';
}
}
echo count($wrong); // this should give me the number of wrong answers, but it does not...
I want to calculate the number of wrong answers and i tried count($wrong);
for this but it does not give me the number of wrong answers.
So what i need: if 3
of the 8
questions are wrong answered, it should give me the number 3
Each txt file looks like this:
02 // 0 is the correct answer, 2 is the answer from the user. I compare 0 with 2. So wrong answer
or
14 // 1 is the correct answer. 4 is the answer of the user. I compare 1 with 4. So wrong answer
or
22 // 2 is the correct answer. 2 is also the answer of the user. So correct answer
$wrong = 0;
is in the foreach loop! so after every iteration, it makes it 0 again.
Your code should look like:
$wrong = 0;
foreach($all_files as $file) {
$each_file = file_get_contents($file);
$choosen_answer = substr($each_file, -1); // last number is the number user has choosen
$correct_answer = substr($each_file, 0,1); // first number is the correct answer
// output the answers
echo '<span class="choosen_answer">'.$choosen_answer.'</span>';
echo '<span class="correct_answer">'.$correct_answer.'</span>';
if($choosen_answer != $correct_answer) { // compare the 2 values
$wrong++;
echo '<span class="wrong text-danger">Wrong</span>';
}
else {
echo '<span class="correct text-success">Correct</span>';
}
}
echo $wrong;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.