0
0
PHPprogramming~10 mins

While loop execution model 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 start a while loop that runs as long as $count is less than 5.

PHP
<?php
$count = 0;
while ([1]) {
    echo $count . "\n";
    $count++;
}
?>
Drag options to blanks, or click blank then click option'
A$count >= 5
B$count < 5
C$count == 5
D$count > 5
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < in the condition
Using == which runs only if $count equals 5
2fill in blank
medium

Complete the code to increment $i by 2 inside the while loop.

PHP
<?php
$i = 0;
while ($i < 10) {
    echo $i . "\n";
    [1];
}
?>
Drag options to blanks, or click blank then click option'
A$i += 2
B$i--
C$i = $i + 1
D$i = 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using $i = 2 which resets the value
Using $i-- which decreases the value
3fill in blank
hard

Fix the error in the while loop condition to avoid an infinite loop.

PHP
<?php
$num = 5;
while ([1]) {
    echo $num . "\n";
    $num--;
}
?>
Drag options to blanks, or click blank then click option'
A$num == 5
B$num = 0
C$num > 5
D$num >= 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using assignment (=) instead of comparison (>=)
Using a condition that never becomes false
4fill in blank
hard

Fill both blanks to create a while loop that prints numbers from 1 to 5.

PHP
<?php
$num = 1;
while ([1]) {
    echo $num . "\n";
    [2];
}
?>
Drag options to blanks, or click blank then click option'
A$num <= 5
B$num < 5
C$num++
D$num += 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using $num < 5 which stops at 4
Incrementing $num by 2 which skips numbers
5fill in blank
hard

Fill all three blanks to create a while loop that prints even numbers from 2 to 10.

PHP
<?php
$num = [1];
while ([2]) {
    echo $num . "\n";
    [3];
}
?>
Drag options to blanks, or click blank then click option'
A2
B$num <= 10
C$num += 2
D$num < 10
Attempts:
3 left
💡 Hint
Common Mistakes
Starting $num at 1 instead of 2
Using $num < 10 which excludes 10
Incrementing by 1 instead of 2