PHP tags and embedding in HTML - Time & Space Complexity
When PHP code is embedded inside HTML, the server processes PHP parts before sending the page.
We want to see how the time to run PHP changes as the PHP code inside HTML grows.
Analyze the time complexity of the following PHP embedded in HTML snippet.
<html>
<body>
<?php
for ($i = 0; $i < $n; $i++) {
echo "<p>Item $i</p>";
}
?>
</body>
</html>
This code prints a list of <p> items inside HTML, repeating $n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs $n times.
- How many times: Exactly $n times, printing one <p> tag each time.
As $n grows, the number of printed <p> tags grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with $n; doubling $n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items printed.
[X] Wrong: "Embedding PHP in HTML makes the code run instantly regardless of size."
[OK] Correct: Even though PHP is inside HTML, the server still runs the PHP code line by line, so more PHP means more work.
Understanding how PHP loops inside HTML affect performance helps you write efficient web pages and explain your code clearly.
"What if we replaced the for-loop with a nested loop inside the PHP tags? How would the time complexity change?"