Bird
0
0

Given the following PHP code:

medium📝 Predict Output Q5 of 15
PHP - Sessions and Cookies
Given the following PHP code:
session_start();
if (empty($_SESSION['visits'])) {
  $_SESSION['visits'] = 1;
} else {
  $_SESSION['visits'] += 1;
}
echo $_SESSION['visits'];

What will be displayed when the page is loaded for the third time in the same session?
A3
B2
C1
D4
Step-by-Step Solution
Solution:
  1. Step 1: First load

    Since $_SESSION['visits'] is empty, it is set to 1 and echoed.
  2. Step 2: Second load

    Variable exists, incremented to 2 and echoed.
  3. Step 3: Third load

    Incremented again to 3 and echoed.
  4. Final Answer:

    3 -> Option A
  5. Quick Check:

    Session variable increments on each load [OK]
Quick Trick: Session variables persist and increment across page loads [OK]
Common Mistakes:
  • Resetting session variable on each load
  • Not calling session_start() before accessing $_SESSION
  • Using isset() instead of empty() incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes