Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q4 of 15
PHP - Sessions and Cookies
What will be the output of this PHP code?
<?php
session_start();
$_SESSION['count'] = ($_SESSION['count'] ?? 0) + 1;
echo $_SESSION['count'];
?>
A1 on first run, increments by 1 on each reload
BAlways 0
CError because $_SESSION['count'] is undefined
DAlways 1 regardless of reloads
Step-by-Step Solution
Solution:
  1. Step 1: Analyze session variable increment

    The code uses null coalescing to set $_SESSION['count'] to 0 if not set, then adds 1.
  2. Step 2: Understand session persistence

    Because session persists, each reload increments the count by 1 starting from 1.
  3. Final Answer:

    1 on first run, increments by 1 on each reload -> Option A
  4. Quick Check:

    Session count increments on reload = 1,2,3... [OK]
Quick Trick: Use null coalescing to initialize session vars safely [OK]
Common Mistakes:
  • Expecting error on undefined session key
  • Thinking session resets on every reload
  • Assuming count stays constant

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes