Elseif ladder execution in PHP - Time & Space 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?
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 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.
As the number of conditions increases, the checks grow roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of conditions.
Time Complexity: O(n)
This means the time to run grows in a straight line as you add more conditions.
[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.
Understanding how conditions are checked helps you explain how your code runs efficiently and shows you can think about performance clearly.
"What if we replaced the elseif ladder with a switch statement? How would the time complexity change?"