0
0
PHPprogramming~10 mins

Foreach loop for arrays in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to loop through the array and print each fruit.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as [1]) {
    echo $fruit . "\n";
}
?>
Drag options to blanks, or click blank then click option'
A$fruit
B$fruits
C$item
D$value
Attempts:
3 left
💡 Hint
Common Mistakes
Using the array variable itself instead of a single element variable.
Using a variable name that is not defined in the loop.
2fill in blank
medium

Complete the code to loop through the array with keys and values.

PHP
<?php
$ages = ['Alice' => 25, 'Bob' => 30];
foreach ($ages as [1] => $age) {
    echo "$name is $age years old.\n";
}
?>
Drag options to blanks, or click blank then click option'
A$value
B$name
C$item
D$key
Attempts:
3 left
💡 Hint
Common Mistakes
Using the value variable instead of the key variable.
Using a variable name that does not match the echo statement.
3fill in blank
hard

Fix the error in the foreach loop to correctly print keys and values.

PHP
<?php
$colors = ['red' => '#FF0000', 'green' => '#00FF00'];
foreach ($colors as $color [1] $hex) {
    echo "$color: $hex\n";
}
?>
Drag options to blanks, or click blank then click option'
A->
B=
C:
D=>
Attempts:
3 left
💡 Hint
Common Mistakes
Using assignment operator = instead of =>.
Using object operator -> or colon : which are incorrect here.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths for words longer than 3 letters.

PHP
<?php
$words = ['cat', 'house', 'dog', 'elephant'];
$lengths = [];
foreach ($words as $word) {
    if ([1]($word) [2] 3) {
        $lengths[$word] = strlen($word);
    }
}
?>
Drag options to blanks, or click blank then click option'
Astrlen
B>
C<
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using count which works on arrays, not strings.
Using < instead of > causing wrong filtering.
5fill in blank
hard

Fill all three blanks to create an associative array with uppercase keys and values greater than 10.

PHP
<?php
$data = ['a' => 5, 'b' => 15, 'c' => 20];
$result = [];
foreach ($data as [1] => [2]) {
    if ([2] > 10) {
        $result[strtoupper([1])] = [2];
    }
}
?>
Drag options to blanks, or click blank then click option'
A$key
B$value
C$val
D$k
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up key and value variable names.
Using inconsistent variable names inside the loop.