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?"
Practice
foreach loop do in PHP when used with an array?Solution
Step 1: Understand the purpose of foreach
The foreach loop is designed to go through each element in an array, one at a time.Step 2: Compare options with foreach behavior
Only It visits each item in the array one by one. correctly describes visiting each item. Others describe actions foreach does not perform.Final Answer:
It visits each item in the array one by one. -> Option BQuick Check:
foreach loops visit all items [OK]
- Thinking foreach only visits first item
- Confusing foreach with array modification functions
- Assuming foreach changes array order
$colors using foreach to get each value?Solution
Step 1: Identify correct foreach syntax
The correct syntax is: foreach (array as value) { ... } with parentheses and 'as' keyword.Step 2: Check each option
foreach ($colors as $color) { echo $color; } matches correct syntax. Options A, B, and D have syntax errors or wrong order.Final Answer:
foreach ($colors as $color) { echo $color; } -> Option CQuick Check:
Correct foreach syntax uses 'foreach (array as value)' [OK]
- Missing parentheses around array and variable
- Using 'in' instead of 'as'
- Swapping variable and array positions
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
echo $fruit . ' ';
}Solution
Step 1: Understand the loop output
The foreach loop prints each fruit followed by a space.Step 2: Combine printed values
Output will be 'apple ' then 'banana ' then 'cherry ' concatenated.Final Answer:
apple banana cherry -> Option AQuick Check:
Each fruit printed with space [OK]
- Expecting commas instead of spaces
- Thinking array prints as string
- Missing spaces between words
$numbers = [1, 2, 3];
foreach ($numbers $num) {
echo $num;
}Solution
Step 1: Check foreach syntax
foreach requires 'as' keyword between array and variable.Step 2: Identify missing keyword
The code misses 'as' between $numbers and $num, causing syntax error.Final Answer:
Missing 'as' keyword in foreach loop. -> Option AQuick Check:
foreach needs 'as' keyword [OK]
- Omitting 'as' keyword
- Confusing variable and array order
- Assuming variables need prior declaration
$items = ['a' => 1, 'b' => 0, 'c' => 3, 'd' => null];, which foreach loop will print only keys with truthy values?Solution
Step 1: Understand truthy values in PHP
Values like 1 and 3 are truthy; 0 and null are falsy.Step 2: Analyze each loop's condition
foreach ($items as $key => $value) { if ($value) echo $key; } prints keys only if value is truthy, matching requirement. Others print keys regardless or check wrong condition.Final Answer:
foreach ($items as $key => $value) { if ($value) echo $key; } -> Option DQuick Check:
Check value truthiness before echo key [OK]
- Printing keys without condition
- Checking for zero instead of truthy
- Not using key => value syntax
Ready to prove it?
Pass the test and this pattern moves unknown
