Logical operators in PHP - Time & Space Complexity
Logical operators combine true or false values to make decisions in code.
We want to see how the time to run code with logical operators changes as input grows.
Analyze the time complexity of the following code snippet.
function checkConditions(array $data) {
foreach ($data as $item) {
if ($item > 10 && $item % 2 === 0) {
echo "Even and greater than 10: $item\n";
}
}
}
This code checks each number in an array to see if it is even and greater than 10.
- Primary operation: Looping through each item in the array.
- How many times: Once for every element in the input array.
As the array gets bigger, the code checks more items one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows.
[X] Wrong: "Logical operators make the code run slower exponentially."
[OK] Correct: Logical operators just combine conditions and run once per item, so they don't multiply the work by input size.
Understanding how logical checks scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we added a nested loop inside the foreach? How would the time complexity change?"