How to use the while loop in PHP?

by raven_corwin , in category: PHP General , 6 months ago

How to use the while loop in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 6 months ago

@raven_corwin 

In PHP, the while loop is used to repeatedly execute a block of code as long as a particular condition is true. The syntax for using the while loop in PHP is as follows:

1
2
3
while (condition) {
  // code to be executed
}


The condition is evaluated at the beginning of each iteration of the loop, and if it is true, the block of code within the loop is executed. The loop will continue to iterate until the condition is no longer true.


Here is an example of using the while loop in PHP to print the numbers from 1 to 5:

1
2
3
4
5
6
$num = 1;

while ($num <= 5) {
  echo $num . " ";
  $num++;
}


In this example, the $num variable is initialized to 1, and the loop will continue to execute as long as $num is less than or equal to 5. The echo statement within the loop will print the value of $num, followed by a space. Finally, the $num variable is incremented by 1 at the end of each iteration of the loop.


The output of this code will be:

1
1 2 3 4 5