Bird
0
0

How can you read a cookie named cart safely to avoid errors if it does not exist?

hard📝 Application Q9 of 15
PHP - Sessions and Cookies
How can you read a cookie named cart safely to avoid errors if it does not exist?
Aecho $_COOKIE['cart'];
BBoth C and D
Cecho $_COOKIE['cart'] ?? 'empty';
Dif (isset($_COOKIE['cart'])) { echo $_COOKIE['cart']; } else { echo 'empty'; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe cookie access

    Accessing a cookie directly without checking may cause undefined index error.
  2. Step 2: Review options for safe reading

    if (isset($_COOKIE['cart'])) { echo $_COOKIE['cart']; } else { echo 'empty'; } uses isset() check, echo $_COOKIE['cart'] ?? 'empty'; uses null coalescing operator, both prevent errors.
  3. Final Answer:

    Both C and D -> Option B
  4. Quick Check:

    Safe cookie read = isset() or ?? operator [OK]
Quick Trick: Use isset() or ?? to safely read cookies [OK]
Common Mistakes:
  • Accessing cookie without checking existence
  • Using only echo without fallback
  • Confusing isset() with empty()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes