0
0
PHPprogramming~10 mins

Why loops are needed in PHP - Test Your Understanding

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

Complete the code to print numbers from 1 to 5 using a loop.

PHP
<?php
for ($i = 1; $i [1] 5; $i++) {
    echo $i . "\n";
}
?>
Drag options to blanks, or click blank then click option'
A<
B>
C>=
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < will only print 1 to 4.
Using > or >= will not run the loop correctly.
2fill in blank
medium

Complete the code to sum numbers from 1 to 10 using a loop.

PHP
<?php
$sum = 0;
for ($num = 1; $num [1] 10; $num++) {
    $sum += $num;
}
echo $sum;
?>
Drag options to blanks, or click blank then click option'
A<=
B<
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < will exclude 10 from the sum.
Using > or >= will not run the loop correctly.
3fill in blank
hard

Fix the error in the loop condition to print even numbers from 2 to 10.

PHP
<?php
for ($i = 2; $i [1] 10; $i += 2) {
    echo $i . "\n";
}
?>
Drag options to blanks, or click blank then click option'
A>
B<
C<=
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < excludes 10 from the output.
Using > or >= will cause the loop not to run.
4fill in blank
hard

Fill both blanks to create an associative array of squares for numbers 1 to 5.

PHP
<?php
$squares = [];
for ($i = 1; $i <= 5; $i++) {
    $squares[[1]] = [2];
}
print_r($squares);
?>
Drag options to blanks, or click blank then click option'
A$i
B$i * $i
C$i + 1
D$i - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using $i + 1 or $i - 1 will give wrong keys or values.
Swapping keys and values causes incorrect array.
5fill in blank
hard

Fill all three blanks to create a filtered array of numbers greater than 3 with their squares.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$result = [];
foreach ($numbers as [1]) {
    if ([1] > 3) {
        $result[[2]] = [3];
    }
}
print_r($result);
?>
Drag options to blanks, or click blank then click option'
A$num
B$num * $num
D$number
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causes errors.
Not filtering numbers greater than 3.