Type casting syntax in PHP - Time & Space Complexity
Let's see how the time needed to change a value's type grows as the input size changes.
We want to know how fast type casting runs when the input gets bigger.
Analyze the time complexity of the following code snippet.
$array = ["1", "2", "3", "4", "5"];
$intArray = [];
foreach ($array as $value) {
$intArray[] = (int) $value;
}
This code converts each string in an array to an integer and stores it in a new array.
- Primary operation: Looping through each element in the array and casting it to an integer.
- How many times: Once for every item in the input array.
Each new item adds one more cast operation, so the total work grows steadily with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 casts |
| 100 | 100 casts |
| 1000 | 1000 casts |
Pattern observation: The work grows in a straight line as the input size grows.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items you convert.
[X] Wrong: "Type casting is instant and does not depend on input size."
[OK] Correct: Each item must be processed one by one, so more items mean more work.
Understanding how simple operations like type casting scale helps you explain code efficiency clearly and confidently.
"What if we changed the array to a nested array and cast each inner value? How would the time complexity change?"