0
0
PHPprogramming~5 mins

Elseif ladder execution in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Elseif ladder execution
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run an elseif ladder changes as the number of conditions grows.

How does checking more conditions affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$number = 7;
if ($number == 1) {
    echo "One";
} elseif ($number == 2) {
    echo "Two";
} elseif ($number == 3) {
    echo "Three";
} elseif ($number == 7) {
    echo "Seven";
} else {
    echo "Other";
}

This code checks a number against several conditions one by one until it finds a match.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each condition in the elseif ladder one after another.
  • How many times: Up to the number of conditions until a match is found or all are checked.
How Execution Grows With Input

As the number of conditions increases, the checks grow roughly in a straight line.

Input Size (n)Approx. Operations
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows directly with the number of conditions.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as you add more conditions.

Common Mistake

[X] Wrong: "The elseif ladder checks all conditions no matter what."

[OK] Correct: The checks stop as soon as one condition matches, so sometimes fewer checks happen.

Interview Connect

Understanding how conditions are checked helps you explain how your code runs efficiently and shows you can think about performance clearly.

Self-Check

"What if we replaced the elseif ladder with a switch statement? How would the time complexity change?"