Bird
0
0

Identify the error in this PHP code snippet for validating an integer input:

medium📝 Debug Q14 of 15
PHP - Superglobals and Web Context
Identify the error in this PHP code snippet for validating an integer input:
$age = $_POST['age'];
if (filter_var($age, FILTER_SANITIZE_INT)) {
    echo "Valid age";
} else {
    echo "Invalid age";
}
AMissing semicolon after echo statements
BFILTER_SANITIZE_INT should be FILTER_VALIDATE_INT
CUsing $_POST without quotes
Dfilter_var() cannot validate integers
Step-by-Step Solution
Solution:
  1. Step 1: Understand difference between sanitize and validate

    FILTER_SANITIZE_INT cleans input by removing non-numeric characters but does not validate if input is a valid integer.
  2. Step 2: Correct filter for validation

    To check if input is a valid integer, use FILTER_VALIDATE_INT instead of FILTER_SANITIZE_INT.
  3. Final Answer:

    FILTER_SANITIZE_INT should be FILTER_VALIDATE_INT -> Option B
  4. Quick Check:

    Validation needs FILTER_VALIDATE_INT, not sanitize [OK]
Quick Trick: Use FILTER_VALIDATE_INT to check integers, not sanitize [OK]
Common Mistakes:
  • Confusing sanitize with validate filters
  • Ignoring filter_var() return values
  • Assuming sanitize validates input

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes