0
0
PHPprogramming~5 mins

Indexed array creation in PHP - Time & Space Complexity

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

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each new element means one more step to add it to the array.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of elements; double the elements, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the array grows in a straight line with the number of items added.

Common Mistake

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

Interview Connect

Understanding how simple loops grow with input size helps you explain and reason about code efficiency clearly in interviews.

Self-Check

"What if we used array_merge inside the loop instead of adding elements one by one? How would the time complexity change?"