0
0
PHPprogramming~5 mins

Nested conditional execution in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested conditional execution
O(1)
Understanding Time Complexity

We want to see how the time a program takes changes when it uses nested conditions.

Specifically, we ask: does adding more conditions inside each other make the program slower as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkNumber(int $num): string {
    if ($num > 0) {
        if ($num % 2 === 0) {
            return "Positive even";
        } else {
            return "Positive odd";
        }
    } else {
        return "Zero or negative";
    }
}
    

This code checks if a number is positive and then if it is even or odd, using nested if statements.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps here, only simple if checks.
  • How many times: Each condition runs once per function call.
How Execution Grows With Input

The number of steps does not increase with the size of the input number.

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

Pattern observation: The steps stay the same no matter how big the number is.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter the input size.

Common Mistake

[X] Wrong: "Nested ifs always make the program slower as input grows."

[OK] Correct: Nested conditions just check one after another once; they do not repeat or grow with input size.

Interview Connect

Understanding how nested conditions affect time helps you explain your code clearly and shows you know when complexity grows or stays steady.

Self-Check

"What if we added a loop inside the nested ifs? How would the time complexity change?"