Associative array creation in PHP - Time & Space Complexity
When we create an associative array in PHP, we want to know how the time it takes grows as we add more items.
We ask: How does adding more key-value pairs affect the work done by the program?
Analyze the time complexity of the following code snippet.
$assocArray = [];
for ($i = 0; $i < $n; $i++) {
$assocArray["key" . $i] = $i;
}
This code creates an associative array by adding n key-value pairs, where keys are strings and values are numbers.
- Primary operation: Adding one key-value pair to the associative array.
- How many times: Exactly
ntimes, once per loop iteration.
Each new item is added one after another, so the total work grows steadily as we add more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insertions |
| 100 | About 100 insertions |
| 1000 | About 1000 insertions |
Pattern observation: The work grows directly in proportion to the number of items added.
Time Complexity: O(n)
This means the time to create the associative array grows linearly with the number of key-value pairs added.
[X] Wrong: "Adding items to an associative array is instant and does not depend on the number of items."
[OK] Correct: Each insertion takes some time, so more items mean more total work, even if each insertion is fast.
Understanding how adding items to an associative array scales helps you explain efficiency in real coding tasks and shows you know how data structures behave.
"What if we used numeric keys instead of string keys? How would the time complexity change?"