Comparison operators (loose and strict) in PHP - Time & Space Complexity
We want to understand how the time it takes to compare values changes as we compare more items.
How does using loose or strict comparison affect the work done when checking many values?
Analyze the time complexity of the following code snippet.
$values = [1, '1', 2, '2', 3, '3'];
$target = 2;
foreach ($values as $value) {
if ($value == $target) { // loose comparison
echo "$value matches loosely\n";
}
if ($value === $target) { // strict comparison
echo "$value matches strictly\n";
}
}
This code checks each value in an array against a target using both loose and strict comparisons.
- Primary operation: Looping through each element in the array and comparing it to the target.
- How many times: Once for each element in the array.
As the number of values grows, the number of comparisons grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The work grows directly with the number of items; doubling items doubles the comparisons.
Time Complexity: O(n)
This means the time to compare grows in a straight line with the number of values checked.
[X] Wrong: "Strict comparison takes more time than loose comparison because it checks types too."
[OK] Correct: Both comparisons happen once per item, so the overall time grows the same way; the difference in checking type is very small and does not change the growth pattern.
Understanding how comparison operations scale helps you explain how your code behaves with bigger data, a skill that shows you think about efficiency clearly.
"What if we changed the array to a nested array and compared inner arrays? How would the time complexity change?"