0
0
PHPprogramming~5 mins

Foreach loop for arrays in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Foreach loop for arrays
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the array gets bigger, the loop runs more times, directly matching the number of items.

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

Pattern observation: The work grows evenly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

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

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave with bigger data.

Self-Check

"What if we nested another foreach loop inside this one to compare every item with every other item? How would the time complexity change?"