Foreach loop for arrays in PHP - Time & Space Complexity
When we use a foreach loop to go through an array, we want to know how the time it takes changes as the array gets bigger.
We ask: How much longer does the program run if the array has more items?
Analyze the time complexity of the following code snippet.
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
echo $number * 2 . "\n";
}
This code goes through each number in the array and prints double its value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop that visits each item in the array.
- How many times: Once for every element in the array.
As the array gets bigger, the loop runs more times, directly matching the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The work grows evenly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the array.
[X] Wrong: "The foreach loop runs in constant time no matter the array size."
[OK] Correct: The loop must visit each item, so more items mean more steps, not the same time.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave with bigger data.
"What if we nested another foreach loop inside this one to compare every item with every other item? How would the time complexity change?"