Why conditional flow is needed in PHP - Performance Analysis
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?
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 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.
Each number is checked once, so work grows directly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time grows evenly as the list gets bigger.
Time Complexity: O(n)
This means the program takes longer in direct proportion to how many numbers it checks.
[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.
Understanding how conditions inside loops affect time helps you explain your code clearly and shows you know how programs scale.
"What if we added another loop inside the if condition? How would the time complexity change?"