Reading — step 1 of 5
Learn
if/elseif/else works as expected. PHP also has an alternative syntax (if: ... endif;) often used in templates.
if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B";
} else {
echo "F";
}
Use === and !==, not == and !=. PHP's == does loose comparison with type juggling: "0" == false is true, and "abc" == 0 is true on PHP 7 (PHP 8 changed this one to false). Our grader runs PHP 7.4, so you will observe the PHP 7 behaviour — one more reason to reach for === and never think about it again. Strict comparison checks both type and value.
$score = 87;
$grade = match(true) {
$score >= 90 => 'A',
$score >= 80 => 'B',
default => 'F',
};
The match expression (PHP 8+) is like switch but returns a value, requires no break, and uses strict (===) comparison.
Grader note:
matchis PHP 8 syntax, and this course's grader runs PHP 7.4 — pasting thematchblock above into an exercise produces a parse error. Know it for modern codebases; useif/elseif/else(orswitch) in the exercises here.
Typing tip:
===is the equals key pressed three times in a row — no spaces between. PHP's===("identical") compares value AND type, while==("loose equals") converts types first —0 == "a"surprises people;0 === "a"never does.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…