0
0
PHPprogramming~20 mins

Foreach loop for arrays in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Foreach Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 ";
}
?>
Aa:Apple b:Banana c:Cherry
B0:Apple 1:Banana 2:Cherry
CApple Banana Cherry
Da b c
Attempts:
2 left
💡 Hint
Remember foreach can give both key and value when looping associative arrays.
Predict Output
intermediate
1: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;
?>
A3
B4
C0
DError
Attempts:
2 left
💡 Hint
Count increases once per loop iteration.
🔧 Debug
advanced
1:30remaining
Identify error in foreach loop syntax
Which option shows the code that will cause a syntax error?
A<?php foreach ($arr as $value) { echo $value; } ?>
B<?php foreach ($arr as $value) echo $value; ?>
C<?php foreach $arr as $value { echo $value; } ?>
D<?php foreach ($arr as $key => $value) { echo $key; } ?>
Attempts:
2 left
💡 Hint
Check the parentheses and keywords in foreach syntax.
Predict Output
advanced
2: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;
    }
}
?>
A1 2 3 4
B1,2,3,4
CArrayArray
D1234
Attempts:
2 left
💡 Hint
Inner loop prints each number without spaces.
🧠 Conceptual
expert
2: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 . ' ';
}
?>
A2 4 4
B2 4 6 3
C2 4 6
D1 2 3
Attempts:
2 left
💡 Hint
Remember that foreach by reference leaves the last reference variable linked.