×

php · level 2 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.