A foreach loop helps you go through each item in an array easily. It saves time and makes your code simple.
Foreach loop for arrays in PHP
<?php $array = ["apple", "banana", "cherry"]; foreach ($array as $item) { // use $item here } ?>
The $item variable holds the current element in the loop.
You can also get the key (index) with foreach ($array as $key => $value).
<?php $fruits = ["apple", "banana", "cherry"]; foreach ($fruits as $fruit) { echo $fruit . "\n"; } ?>
<?php $emptyArray = []; foreach ($emptyArray as $item) { echo $item; } // Nothing happens because array is empty ?>
<?php $numbers = [10]; foreach ($numbers as $number) { echo $number . "\n"; } ?>
<?php $colors = ["red", "green", "blue"]; foreach ($colors as $index => $color) { echo "Color at index $index is $color\n"; } ?>
This program shows the array before looping and then prints each item using foreach.
<?php $shoppingList = ["milk", "bread", "eggs"]; echo "Before loop:\n"; print_r($shoppingList); echo "\nUsing foreach loop to print items:\n"; foreach ($shoppingList as $item) { echo "Item: $item\n"; } ?>
Time complexity is O(n) because it visits each element once.
Space complexity is O(1) extra space since it uses the existing array.
Common mistake: modifying the array inside the foreach can cause unexpected results.
Use foreach when you want to read or process each element simply. Use for loop if you need index control or to modify array size.
Foreach loops make it easy to visit every item in an array.
You can get just the value or both key and value.
It works well even if the array is empty or has one item.
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
