$_REQUEST behavior in PHP - Time & Space Complexity
When using $_REQUEST in PHP, it's important to understand how accessing this superglobal affects performance.
We want to know how the time to get data from $_REQUEST grows as the input size changes.
Analyze the time complexity of the following code snippet.
// Accessing multiple keys from $_REQUEST
foreach ($keys as $key) {
$value = $_REQUEST[$key] ?? null;
// process $value
}
This code loops through a list of keys and fetches each corresponding value from $_REQUEST.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each key to access
$_REQUESTvalues. - How many times: Once for each key in the
$keysarray.
Each additional key means one more access to $_REQUEST. So, the work grows directly with the number of keys.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 accesses to $_REQUEST |
| 100 | 100 accesses to $_REQUEST |
| 1000 | 1000 accesses to $_REQUEST |
Pattern observation: The number of operations increases evenly as the input size grows.
Time Complexity: O(n)
This means the time to access values from $_REQUEST grows in direct proportion to how many keys you look up.
[X] Wrong: "Accessing $_REQUEST is always instant and does not depend on input size."
[OK] Correct: While each access is fast, doing many accesses adds up, so total time depends on how many keys you check.
Understanding how superglobals like $_REQUEST behave helps you write efficient PHP code and shows you can think about performance in real projects.
"What if we accessed $_POST directly instead of $_REQUEST? How would the time complexity change?"