Array merge and combine in PHP - Time & Space Complexity
When we merge or combine arrays in PHP, the time it takes depends on how many items are involved.
We want to understand how the work grows as the arrays get bigger.
Analyze the time complexity of the following code snippet.
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$result = array_merge($array1, $array2);
$combined = array_combine($array1, $array2);
This code merges two arrays into one and then combines them to create a key-value pair array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing each array to copy or pair elements.
- How many times: Each element in both arrays is visited once during merge and once during combine.
As the size of the arrays grows, the work grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 for merge + 10 for combine) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The operations increase linearly as the arrays get bigger.
Time Complexity: O(n)
This means the time to merge and combine grows in a straight line with the number of elements.
[X] Wrong: "Merging two arrays takes constant time no matter their size."
[OK] Correct: The function must look at every element to copy or pair it, so bigger arrays take more time.
Understanding how array operations scale helps you explain your code choices clearly and confidently in interviews.
"What if we merged three arrays instead of two? How would the time complexity change?"