Challenge - 5 Problems
Foreach Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of foreach loop with associative array
What is the output of this PHP code?
PHP
<?php $fruits = ['a' => 'Apple', 'b' => 'Banana', 'c' => 'Cherry']; foreach ($fruits as $key => $value) { echo "$key:$value "; } ?>
Attempts:
2 left
💡 Hint
Remember foreach can give both key and value when looping associative arrays.
✗ Incorrect
The foreach loop iterates over each key-value pair. Using 'as $key => $value' prints the key and value separated by a colon.
❓ Predict Output
intermediate1:30remaining
Count iterations in foreach loop
What is the value of $count after this code runs?
PHP
<?php $numbers = [10, 20, 30, 40]; $count = 0; foreach ($numbers as $num) { $count++; } echo $count; ?>
Attempts:
2 left
💡 Hint
Count increases once per loop iteration.
✗ Incorrect
The foreach loop runs once for each element in the array, so $count increments 4 times.
🔧 Debug
advanced1:30remaining
Identify error in foreach loop syntax
Which option shows the code that will cause a syntax error?
Attempts:
2 left
💡 Hint
Check the parentheses and keywords in foreach syntax.
✗ Incorrect
Option C misses parentheses around $arr and the 'foreach' keyword requires parentheses enclosing the array and variable.
❓ Predict Output
advanced2:00remaining
Output with nested foreach loops
What is the output of this PHP code?
PHP
<?php $matrix = [[1,2],[3,4]]; foreach ($matrix as $row) { foreach ($row as $num) { echo $num; } } ?>
Attempts:
2 left
💡 Hint
Inner loop prints each number without spaces.
✗ Incorrect
The nested loops print each number consecutively without spaces, resulting in '1234'.
🧠 Conceptual
expert2:30remaining
Behavior of foreach with reference variable
What will be the output of this PHP code?
PHP
<?php $arr = [1, 2, 3]; foreach ($arr as &$value) { $value *= 2; } foreach ($arr as $value) { echo $value . ' '; } ?>
Attempts:
2 left
💡 Hint
Remember that foreach by reference leaves the last reference variable linked.
✗ Incorrect
The first loop doubles values by reference, making $arr=[2,4,6] and leaving $value as reference to $arr[2]. The second loop assigns to $value (modifying $arr[2]): 2 (sets to 2, echo 2), 4 (sets to 4, echo 4), 4 (echo 4).