0
0
PHPprogramming~5 mins

Associative array creation in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Associative array creation
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Adding one key-value pair to the associative array.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each new item is added one after another, so the total work grows steadily as we add more items.

Input Size (n)Approx. Operations
10About 10 insertions
100About 100 insertions
1000About 1000 insertions

Pattern observation: The work grows directly in proportion to the number of items added.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the associative array grows linearly with the number of key-value pairs added.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we used numeric keys instead of string keys? How would the time complexity change?"