Locked lesson.
About this lesson
Let's write some code to determine if the answer is right or wrong.
Exercise files
Download this lesson’s related exercise files.
Right and Wrong Logic.docx59.4 KB Right and Wrong Logic - Solution.docx
59.7 KB
Quick reference
Right and Wrong Logic
Now it's time to determine the right answer and test our answer vs the right answer.
When to use
We'll use a basic if/else statement.
Instructions
Our code so far...
<html>
<head>
<title>Math Flashcards!</title>
</head>
<body>
<center>
<h1>Addition</h1>
<h1>
<?php
$num1 = rand(1,10);
$num2 = rand(1,10);
echo $num1 . " + " . $num2;
?>
</h1>
<br/><br/>
<?php
$correct_answer = $_POST["num1"] + $_POST["num2"];
if($correct_answer == $_POST["answer"]){
echo "Correct! " . $_POST["num1"] . " + " . $_POST["num2"] . " = " . $_POST["answer"];
}else {
echo "Wrong! " . $_POST["num1"] . " + " . $_POST["num2"] . " = " . $correct_answer . " Not " . $_POST["answer"];
}
?>
<br/><br/><br/>
<form method="post" action="/">
<input name="num1" type="hidden" value="<?php echo $num1; ?>">
<input name="num2" type="hidden" value="<?php echo $num2; ?>">
Answer: <input name="answer"> <button>Submit</button> <button>New Card </button>
</form>
</center>
</body>
</html>
Hints & tips
- First determine what the right answer should be
- Then test your answer against the right answer with an if/else statement
Lesson notes are only available for subscribers.