Bird
0
0

Analyze this PHP code:

medium📝 Predict Output Q5 of 15
PHP - Sessions and Cookies
Analyze this PHP code:
<?php
session_start();
if (!isset($_SESSION['visits'])) {
  $_SESSION['visits'] = 1;
} else {
  $_SESSION['visits'] += 1;
}
echo $_SESSION['visits'];
?>

What will be displayed on the fourth page load?
A4
B3
C1
DUndefined index error
Step-by-Step Solution
Solution:
  1. Step 1: Start the session

    session_start() resumes the session to access stored variables.
  2. Step 2: Check if 'visits' is set

    On the first load, $_SESSION['visits'] is not set, so it is initialized to 1.
  3. Step 3: Increment on subsequent loads

    On each following load, the value increments by 1.
  4. Step 4: Calculate value on fourth load

    Loads: 1st = 1, 2nd = 2, 3rd = 3, 4th = 4.
  5. Final Answer:

    4 -> Option A
  6. Quick Check:

    Session variable increments correctly each load [OK]
Quick Trick: Session variables persist and increment across page loads [OK]
Common Mistakes:
  • Not calling session_start() before accessing session variables
  • Resetting session variables on each load
  • Miscounting the number of increments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes