0
0
PHPprogramming~5 mins

Foreach loop for arrays in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Afor
Bforeach
Cwhile
Dloop
How do you access the key and value inside a foreach loop?
Aforeach ($array as $key => $value)
Bforeach ($array as $value => $key)
Cforeach ($array as $value)
Dforeach ($array as $key)
What will this code output? <br> $nums = [1, 2, 3]; foreach ($nums as $n) { echo $n; }
A123
B1 2 3
CArray
DError
How do you change values inside a foreach loop?
AYou cannot change values in foreach
BUse $GLOBALS
CUse & before the value variable
DUse a for loop instead
What happens if the array is empty in a foreach loop?
AIt runs infinitely
BIt runs once with null
CIt throws an error
DThe loop does not run
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.