What is the best way to calculate and display quiz results in PHP, including a percentage of correct answers?
To calculate and display quiz results in PHP, including a percentage of correct answers, you can first count the total number of questions and the number of correct answers submitted by the user. Then, calculate the percentage of correct answers by dividing the number of correct answers by the total number of questions and multiplying by 100. Finally, display the results to the user.
<?php
// Sample quiz results
$totalQuestions = 10;
$correctAnswers = 8;
// Calculate percentage of correct answers
$percentage = ($correctAnswers / $totalQuestions) * 100;
// Display quiz results
echo "You answered $correctAnswers out of $totalQuestions questions correctly.<br>";
echo "Your score is: $percentage%";
?>
Related Questions
- How can PHP developers improve the efficiency and security of their database queries in their code?
- How can the use of sprintf in a MySQL query in PHP be beneficial, and what are the differences between %s and %u in this context?
- What are some alternative methods to ensure that users accessing a website from an external source are legitimate in PHP?