0
0
PHPprogramming~5 mins

Logical operators in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Logical operators
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping through each item in the array.
  • How many times: Once for every element in the input array.
How Execution Grows With Input

As the array gets bigger, the code checks more items one by one.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input size grows.

Common Mistake

[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.

Interview Connect

Understanding how logical checks scale helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

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