Loose comparison vs strict comparison in PHP - Performance Comparison
We want to understand how comparing values in PHP costs time as the input grows.
Specifically, how loose and strict comparisons behave when checking many items.
Analyze the time complexity of the following code snippet.
$array = [1, 2, '3', 4, '5'];
$search = 3;
foreach ($array as $item) {
if ($item == $search) { // loose comparison
echo "Found with loose comparison\n";
}
if ($item === $search) { // strict comparison
echo "Found with strict comparison\n";
}
}
This code checks each item in an array against a search value using both loose and strict comparisons.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each array element and comparing it to the search value.
- How many times: Once for each item in the array (n times).
As the array gets bigger, the number of comparisons grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 comparisons (2 per item) |
| 100 | 200 comparisons |
| 1000 | 2000 comparisons |
Pattern observation: The total work doubles the number of items because each item is compared twice.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items to check.
[X] Wrong: "Strict comparison is always slower because it checks types."
[OK] Correct: Both comparisons happen once per item, so their time grows the same way with input size.
Understanding how simple operations like comparisons scale helps you reason about code efficiency in real projects.
"What if we replaced the array with a nested array and compared inner arrays? How would the time complexity change?"