If statement execution flow in PHP - Time & Space Complexity
We want to see how the time it takes to run an if statement changes as the input changes.
Specifically, does adding more data make the if statement take longer?
Analyze the time complexity of the following code snippet.
$number = 10;
if ($number > 0) {
echo "Positive number";
} else {
echo "Zero or negative number";
}
This code checks if a number is positive and prints a message based on that.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single if condition check
- How many times: Exactly once per run
The if statement runs once no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same even if input grows.
Time Complexity: O(1)
This means the time to run the if statement does not change with input size.
[X] Wrong: "If statements take longer when input is bigger."
[OK] Correct: The if condition runs once regardless of input size, so time stays the same.
Understanding that simple decisions like if statements run in constant time helps you explain code efficiency clearly and confidently.
"What if the if statement was inside a loop that runs n times? How would the time complexity change?"