The While Loop in PHP
The while loop will execute as long as the expression passed to it as a parameter is true. It allows for an arbitrary number of iterations. Here is its syntax:
<?php
while (statement) {
/*
execute this code cyclically
at the beginning of each cycle, check the expression in parentheses
*/
}
?>
The loop will end when the expression is no longer true. If it was false initially, it will not execute even once.
Let's sequentially output numbers from one to five using a while loop as an example:
<?php
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
?>
And now let's do a countdown:
<?php
$i = 10;
while ($i > 0) {
echo $i;
$i--;
}
?>
And now let's divide a given number by 2 as many times as needed until the result becomes less than 10:
<?php
$num = 500;
while ($num > 10) {
$num = $num / 2;
}
echo $num; // result
?>
Display numbers from 1 to 100 on the screen.
Display numbers from 11 to 33 on the screen.
Display numbers from 100 to 1 on the screen.
Given a number num with some initial value.
Multiply it by 3 as many times as needed until the multiplication result becomes greater than 1000.
What number will you get? Count the number of iterations required for this.