Bird
0
0

Which code snippet correctly implements this using $_POST?

hard📝 Application Q8 of 15
PHP - Superglobals and Web Context
You want to create a PHP script that processes a form with fields name and age. If age is missing or empty, it should print "Age is required". Which code snippet correctly implements this using $_POST?
Aif ($_POST['age']) { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; }
Bif ($_POST['age'] == '') { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; }
Cif (isset($_POST['age'])) { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; }
Dif (empty($_POST['age'])) { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; }
Step-by-Step Solution
Solution:
  1. Step 1: Check for empty or missing age

    Using empty() checks if age is missing or empty string, which is correct.
  2. Step 2: Validate other options

    if ($_POST['age'] == '') { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; } only checks empty string, not missing key; if (isset($_POST['age'])) { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; } reverses logic; if ($_POST['age']) { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; } treats any value as true incorrectly.
  3. Final Answer:

    if (empty($_POST['age'])) { echo 'Age is required'; } else { echo $_POST['name'] . ', ' . $_POST['age']; } -> Option D
  4. Quick Check:

    Use empty() to check missing or empty POST fields [OK]
Quick Trick: Use empty() to check if POST field is missing or blank [OK]
Common Mistakes:
  • Using isset() alone misses empty strings
  • Incorrect if condition logic
  • Not handling missing keys properly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes