0
0
PHPprogramming~5 mins

Why conditional flow is needed in PHP - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why conditional flow is needed
O(n)
Understanding Time Complexity

We want to see how adding choices in code affects how long it takes to run.

Does checking conditions slow down the program as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkNumbers(array $numbers) {
    foreach ($numbers as $num) {
        if ($num % 2 === 0) {
            echo "$num is even\n";
        } else {
            echo "$num is odd\n";
        }
    }
}
    

This code checks each number in a list and prints if it is even or odd.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array.
  • How many times: Once for every number in the list.
How Execution Grows With Input

Each number is checked once, so work grows directly with the list size.

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

Pattern observation: The time grows evenly as the list gets bigger.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in direct proportion to how many numbers it checks.

Common Mistake

[X] Wrong: "Adding an if-else inside the loop makes the program much slower, like squared time."

[OK] Correct: The if-else just picks one path per item; it doesn't add extra loops, so time still grows linearly.

Interview Connect

Understanding how conditions inside loops affect time helps you explain your code clearly and shows you know how programs scale.

Self-Check

"What if we added another loop inside the if condition? How would the time complexity change?"