How to use while loop in PHP

In this article, I will explain how the while loop can be used in PHP.
  • 2116

while Loop in PHP

  • The while loop executes a block of code while a condition is true.

  • The while statement is simple, it executes the statement repeatedly as long as the end of condition.

  • In the while loop, condition is checked every time at the beginning of the loop.

Syntax

while (condition)
  {
  code to be executed;
  }

When the condition is true then the code block will be executed. After the code has executed the condition will again be evaluated and the loop will continue until the condition is found to be false.

Example

The following example show a loop that starts with a=1. The loop will continue to run as long as a is less than, or equal to 10. I will increase by 1 each time the loop runs.

<html>

<body>

<h2 style="color: blueviolet;">While Loop example</h2>

    <?php

    $a=1;

    while($a<=10)

    {

    echo "The number is " . $a . "<br />";

    $a++;

    }

    ?>

</body>

</html>

 

Output

while loop.jpg

You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 
© 2019 DotNetHeaven. All rights reserved.