0
0
PHPprogramming~5 mins

If statement execution flow in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If statement execution flow
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single if condition check
  • How many times: Exactly once per run
How Execution Grows With Input

The if statement runs once no matter the input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The number of operations stays the same even if input grows.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if statement does not change with input size.

Common Mistake

[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.

Interview Connect

Understanding that simple decisions like if statements run in constant time helps you explain code efficiency clearly and confidently.

Self-Check

"What if the if statement was inside a loop that runs n times? How would the time complexity change?"