String concatenation operator in PHP - Time & Space Complexity
When we join strings together in PHP using the concatenation operator, it takes some time depending on the size of the strings.
We want to understand how the time to join strings grows as the strings get longer or as we join more strings.
Analyze the time complexity of the following code snippet.
$string = "";
for ($i = 0; $i < $n; $i++) {
$string .= "a";
}
This code builds a string by adding the letter "a" one by one, repeating $n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding one character to the string using concatenation inside a loop.
- How many times: The concatenation happens once per loop, so $n times.
Each time we add a character, PHP creates a new string by copying the old string and adding the new character.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 55 (1+2+...+10) |
| 100 | About 5,050 |
| 1000 | About 500,500 |
Pattern observation: The total work grows roughly like the square of n because each concatenation copies the whole string built so far.
Time Complexity: O(n²)
This means the time to build the string grows roughly with the square of the number of characters added.
[X] Wrong: "Concatenating strings in a loop is always fast and takes time proportional to n."
[OK] Correct: Each concatenation copies the entire string so far, making the total time grow much faster than just n.
Understanding how string joining works helps you write efficient code and explain your choices clearly in real projects or interviews.
"What if we used an array to collect characters and joined them once at the end? How would the time complexity change?"