Ternary operator in PHP - Time & Space Complexity
Let's see how using the ternary operator affects how long a PHP program takes to run.
We want to know if it changes the work done when the input grows.
Analyze the time complexity of the following code snippet.
$age = 20;
$status = ($age >= 18) ? 'adult' : 'minor';
echo $status;
This code checks if a person is an adult or minor using the ternary operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single condition check using the ternary operator.
- How many times: Exactly once, no loops or repeated steps.
Since the ternary operator runs just one check, the work stays the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the ternary operator takes the same amount of time no matter how big the input is.
[X] Wrong: "Using the ternary operator makes the program slower as input grows because it adds extra checks."
[OK] Correct: The ternary operator only does one quick check and does not repeat, so it does not slow down the program as input grows.
Understanding simple operations like the ternary operator helps you explain how small code parts affect performance, a useful skill in coding and interviews.
"What if we used a ternary operator inside a loop that runs n times? How would the time complexity change?"