PHP
Checking answers
Write a method that compares the user's answer to the correct one.
A method to check the answer
You'll add an isCorrect(int $choice): bool method to the Question class. This method compares the user's chosen index with the correct answer index and returns true or false.
In PHP, comparing two values with === (strict equality) is safer. === checks both type and value; for example 0 == "0" is true but 0 === "0" is false. Comparing answer indexes strictly avoids unexpected results.
Returning with strict comparison
Inside the method you write return $choice === $this->answerIndex;. If the user picked the correct index it returns true, otherwise false.
To call the method you write $q->isCorrect(0); 0 means the user picked the first option. To print the result, the ternary operator is handy: echo $q->isCorrect(0) ? "correct" : "wrong";. This gives a one-line conditional output instead of if-else.
Exercise Add the isCorrect method
Add a public function isCorrect(int $choice): bool method to the Question class. Inside it, return the strict comparison return $choice === $this->answerIndex;. Then call the method on the $q instance: change the last line to echo $q->isCorrect(0) ? "correct" : "wrong";.
Show example solution
bool { return $choice === $this->answerIndex; } to the class. Change the last line to echo $q->isCorrect(0) ? "correct" : "wrong";.
Example solution:
<?php
// Add answer checking to the Question class
class Question {
public string $text = "";
public array $options = [];
public int $answerIndex = 0;
public function __construct(string $text, array $options, int $answerIndex) {
$this->text = $text;
$this->options = $options;
$this->answerIndex = $answerIndex;
}
public function isCorrect(int $choice): bool {
return $choice === $this->answerIndex;
}
}
$q = new Question("What is PHP?", ["Scripting language", "Database", "Browser"], 0);
echo $q->isCorrect(0) ? "correct" : "wrong";
Test yourself
-
What is the difference between === and ==?
- They are the same, no difference
- === is only used for strings
- === checks type and value, == only value
- == checks type, === checks value
Show answer
=== checks type and value, == only value — Correct. === checks both type and value; == only checks value and may convert types.
-
Complete the isCorrect return statement
public function isCorrect(int $choice): bool {
return ____;
}
Show answer
public function isCorrect(int $choice): bool {
return $choice === $this->answerIndex;
}
-
Match the comparison concepts
- ===
- Strict equality
- ==
- Loose equality
- bool
- Boolean type
- return
- Returns a value
Next lesson: Computing the score