Type juggling in PHP - Time & Space Complexity
When PHP changes data types automatically, it does some work behind the scenes.
We want to see how this work grows when the input size changes.
Analyze the time complexity of the following code snippet.
$values = ["10", "20", "30", "40", "50"];
$sum = 0;
foreach ($values as $val) {
$sum += $val; // PHP converts string to number here
}
echo $sum;
This code adds numbers stored as strings by PHP converting them automatically.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element and converting string to number.
- How many times: Once for each item in the array.
Each new item adds one conversion and addition step.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 conversions and additions |
| 100 | 100 conversions and additions |
| 1000 | 1000 conversions and additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time needed grows in a straight line as the list gets longer.
[X] Wrong: "Type juggling happens instantly and does not affect performance."
[OK] Correct: Each conversion takes time, so more items mean more work.
Understanding how PHP handles type changes helps you write clearer and more efficient code.
"What if the array contained nested arrays instead of strings? How would the time complexity change?"