0
0
PHPprogramming~5 mins

If-else execution flow in PHP - Time & Space Complexity

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

Scenario Under Consideration

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

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
How Execution Grows With Input

The time to run this code stays about the same no matter what number you give it.

Input Size (n)Approx. Operations
103 checks
1003 checks
10003 checks

Pattern observation: The number of checks does not grow with input size; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays the same no matter how big the input number is.

Common Mistake

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

Interview Connect

Understanding that simple if-else checks run in constant time helps you explain how decisions in code affect speed.

Self-Check

"What if we added a loop that runs the if-else check multiple times? How would the time complexity change?"