A. Echoing variable outside the if block without initialization
B. Using $_POST without checking if 'email' exists
C. Missing semicolon after echo statement
D. Incorrect request method check
Solution
Step 1: Analyze variable scope and initialization
The variable $email is assigned only inside the if block, so if the request method is not POST, it remains undefined.
Step 2: Check usage of variable outside if block
Echoing $email outside the if block without initialization causes a notice or error if the form is not submitted.
Final Answer:
Echoing variable outside the if block without initialization -> Option A
Quick Check:
Use variable only after initialization [OK]
Hint: Initialize variables before use outside condition [OK]
Common Mistakes:
Assuming variables inside if exist outside
Not initializing variables before echo
Ignoring request method check
5. You want to keep the user's input visible in the form field after submission to improve user experience. Which PHP code snippet correctly achieves this for a text input named username?
hard
A. <input type='text' name='username' value='<?php echo $_POST['username']; ?>'>
B. <input type='text' name='username' value='<?php echo $_GET['username']; ?>'>
C. <input type='text' name='username' value='<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>'>
D. <input type='text' name='username' value='<?php echo $_POST['username'] ?? 'Guest'; ?>'>
Solution
Step 1: Ensure safe output in HTML attribute
Using htmlspecialchars() prevents HTML injection and ensures special characters display correctly.
Step 2: Use null coalescing operator to avoid undefined index
$_POST['username'] ?? '' ensures the value is empty string if not set, avoiding errors.