php · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
does the fiddly checks for you.
Checking an email address by hand is surprisingly hard. filter_var comes with ready-made rules. filter_var($email, FILTER_VALIDATE_EMAIL) gives back the email if it looks real, and false if it does not.
FILTER_VALIDATE_EMAIL is a : a named value that never changes, written in capitals. FILTER_VALIDATE_INT is another. It turns "42" into the integer 42, and gives false for "4.5" or "lots".
Always check the answer with === false. A valid answer of "0" comes back as 0, and if treats 0 like false too.
<?php
$_POST = ["email" => "jo@example.com", "age" => "12"];
$email = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
$age = filter_var($_POST["age"], FILTER_VALIDATE_INT);
if ($email === false) {
echo "That email does not look right.\n";
} else {
echo "Email: $email\n";
}
echo $age === false ? "Age must be a whole number.\n" : "Age next year: " . ($age + 1) . "\n"; A filter checks that an email looks right, not that it really exists, which is why real sites also send a check email.
guess first
Four answers, one rule. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$answers = ["7", "seven", "7.5", "0"];
foreach ($answers as $answer) {
$number = filter_var($answer, FILTER_VALIDATE_INT);
echo $number === false ? "no " : "yes ";
}
your turn
Your turn. Join the mailing list.
Type an email address and run it. Then try one with a mistake, like a missing @, and run it again.
fix it
A goalless match will not save. Can you fix it?
- 0 is a whole number, so the filter gives back 0. What does
!make of 0? !0istrue, becauseiftreats 0 likefalse. Ask aboutfalseitself instead.- Change line 4 to
if ($goals === false) {, then press run.
nailed it
your filters catch the tricky cases. :D
filter_vargives back the clean value orfalse.- Use
FILTER_VALIDATE_EMAILandFILTER_VALIDATE_INT. - Always check with
=== false, because 0 is valid.
new words in your collection
- filter_var
- constant
This lesson isn’t saved. A free account remembers every lesson you finish.