Indexed array creation in PHP - Time & Space Complexity
Let's see how the time it takes to create an indexed array changes as the number of elements grows.
We want to know how the work increases when we add more items to the array.
Analyze the time complexity of the following code snippet.
$array = [];
for ($i = 0; $i < $n; $i++) {
$array[] = $i;
}
This code creates an empty array and adds numbers from 0 up to n-1 one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding one element to the array inside the loop.
- How many times: Exactly n times, once for each number from 0 to n-1.
Each new element means one more step to add it to the array.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of elements; double the elements, double the work.
Time Complexity: O(n)
This means the time to create the array grows in a straight line with the number of items added.
[X] Wrong: "Adding elements to an array inside a loop is instant and does not depend on the number of elements."
[OK] Correct: Each addition takes a small step, so more elements mean more steps, making the total time grow with n.
Understanding how simple loops grow with input size helps you explain and reason about code efficiency clearly in interviews.
"What if we used array_merge inside the loop instead of adding elements one by one? How would the time complexity change?"