Why variables do not persist between requests in PHP - Performance Analysis
When a PHP script runs, it starts fresh each time a user visits a page.
We want to understand why variables don't keep their values between these visits.
Analyze the time complexity of the following code snippet.
<?php
$counter = 0;
$counter++;
echo $counter;
?>
This code sets a variable, increases it, and shows it each time the page loads.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Assigning and incrementing a variable once per request.
- How many times: Exactly once each time the script runs (each page load).
Each time the page loads, the script runs from the start, so the variable resets.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 page load | 1 increment operation |
| 10 page loads | 10 separate increments, each starting fresh |
| 100 page loads | 100 separate increments, no memory of past values |
Pattern observation: The variable does not remember past increments because each run is independent.
Time Complexity: O(1)
This means the script does a fixed amount of work each time, no matter how many times it runs.
[X] Wrong: "The variable will keep increasing every time the page reloads."
[OK] Correct: Each page load starts a new script with fresh variables, so previous values are lost.
Understanding this helps you explain how web servers handle requests and why you need special ways to save data between visits.
"What if we used sessions or files to store the variable? How would the time complexity change?"