Recall & Review
beginner
What is a foreach loop used for in PHP?
A foreach loop is used to easily go through each item in an array, one by one, without needing to know the array's size.
Click to reveal answer
beginner
How do you write a basic foreach loop to print all values in an array named $fruits?
foreach ($fruits as $fruit) { echo $fruit; }
Click to reveal answer
intermediate
What does this code do? <br>
foreach ($colors as $key => $value) { echo "$key: $value"; }It goes through the $colors array and prints each key and its matching value, like 'red: #ff0000'.
Click to reveal answer
intermediate
Can you modify array values inside a foreach loop in PHP?
Yes, but you must use a reference by adding & before the value variable, like: foreach ($arr as &$value) { $value = $value * 2; }
Click to reveal answer
beginner
What happens if you use foreach on an empty array?
The loop does not run at all because there are no items to go through.
Click to reveal answer
Which keyword starts a foreach loop in PHP?
✗ Incorrect
The foreach keyword is used specifically to loop through arrays in PHP.
How do you access the key and value inside a foreach loop?
✗ Incorrect
The correct syntax to get both key and value is foreach ($array as $key => $value).
What will this code output? <br>
$nums = [1, 2, 3]; foreach ($nums as $n) { echo $n; }✗ Incorrect
The loop prints each number one after another without spaces, so output is '123'.
How do you change values inside a foreach loop?
✗ Incorrect
Adding & before the value variable lets you modify the original array values inside the loop.
What happens if the array is empty in a foreach loop?
✗ Incorrect
If the array is empty, foreach simply skips the loop body.
Explain how a foreach loop works with arrays in PHP.
Think about how you would tell a friend to read each item in a list one by one.
You got /4 concepts.
Describe how to modify array values inside a foreach loop and why you need a reference.
Imagine you want to change the original list items, not just copies.
You got /3 concepts.