Bird
0
0

You want to check if a variable $x exists and is not null, but also want to treat the value 0 as valid (not empty). Which combination of PHP functions correctly achieves this?

hard📝 Application Q15 of 15
PHP - Type Handling
You want to check if a variable $x exists and is not null, but also want to treat the value 0 as valid (not empty). Which combination of PHP functions correctly achieves this?
Aif (isset($x) && $x !== null) { ... }
Bif (isset($x) && !empty($x)) { ... }
Cif (!is_null($x) && !empty($x)) { ... }
Dif (!empty($x) || isset($x)) { ... }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    We want to check if $x exists and is not null, but 0 should be valid (not treated as empty).
  2. Step 2: Analyze each option

    if (isset($x) && !empty($x)) { ... } fails because empty(0) is true, so 0 would be excluded. if (isset($x) && $x !== null) { ... } checks if $x is set and not null, allowing 0. if (!is_null($x) && !empty($x)) { ... } excludes 0 because of empty($x). if (!empty($x) || isset($x)) { ... } uses OR, which can be true even if $x is empty or null.
  3. Final Answer:

    if (isset($x) && $x !== null) { ... } -> Option A
  4. Quick Check:

    Use isset and strict null check to allow 0 [OK]
Quick Trick: Use isset and !== null to allow zero values [OK]
Common Mistakes:
  • Using empty excludes zero values
  • Using OR instead of AND
  • Confusing is_null with isset

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes