Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q4 of 15
PHP - Sessions and Cookies
What will be the output of the following PHP code?
setcookie('user', 'Alice');
if(isset($_COOKIE['user'])) {
echo 'User is ' . $_COOKIE['user'];
} else {
echo 'User cookie not set';
}
AUser cookie not set
BNo output
CUndefined index error
DUser is Alice
Step-by-Step Solution
Solution:
  1. Step 1: Understand when cookies are available

    Cookies set by setcookie() are sent to the browser and only available in $_COOKIE on the next request, not the current script.
  2. Step 2: Analyze the code behavior

    The isset($_COOKIE['user']) check will fail because the cookie is not yet available in the current request.
  3. Final Answer:

    User cookie not set -> Option A
  4. Quick Check:

    Cookies available next request = User cookie not set [OK]
Quick Trick: Cookies appear in $_COOKIE only on next page load [OK]
Common Mistakes:
  • Expecting cookie immediately after setcookie()
  • Ignoring that cookies require a new request
  • Assuming $_COOKIE updates instantly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes