If-else execution flow in PHP - Time & Space Complexity
We want to understand how the time it takes to run if-else statements changes as the input changes.
Specifically, we ask: does adding more conditions or inputs make the program slower?
Analyze the time complexity of the following code snippet.
function checkNumber($num) {
if ($num > 0) {
return "Positive";
} elseif ($num < 0) {
return "Negative";
} else {
return "Zero";
}
}
This code checks if a number is positive, negative, or zero and returns a string accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single if-else checks (no loops or recursion)
- How many times: Each condition is checked once per function call
The time to run this code stays about the same no matter what number you give it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 checks |
| 100 | 3 checks |
| 1000 | 3 checks |
Pattern observation: The number of checks does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the time to run the code stays the same no matter how big the input number is.
[X] Wrong: "If I give a bigger number, the code will take longer because it has to check more things."
[OK] Correct: The code only checks fixed conditions once, so bigger numbers don't add more checks.
Understanding that simple if-else checks run in constant time helps you explain how decisions in code affect speed.
"What if we added a loop that runs the if-else check multiple times? How would the time complexity change?"