While Loop in PHP

Download This Tutorial in PDF

While Loop in PHP

While loop executes a block of statements as long as the condition that is defined is true.

In the example below, we have set a variable $x to 1.The while loop will continue to run as long as the value of $x  is less than or equal to 10. Variable “$x” is increment by 1 each time the loop runs $x++.

Flowchart of While Loop. 

while loop in php
Figure: while loop in PHP.

Example of While loop in PHP.

An example program to demonstrate the while loop.

The output of While loop program in PHP.

The value is:1
The value is:2
The value is :3
The value is:4
The value is:5
The value is:6
The value is:7
The value is:8
The value is:9
The value is:10



<?phpPHP  opening.
  $x=1;Variable is declared and its value is initialized.
 while($x<=10)Here checking the condition.
 {While loop opening.
                 echo “The value is :$x<br>”;Code within Loop . Prints the message.
                 $x++;Value of variable $x is incremented by 1.
 }Loop ends.
?>PHP closing.

Comparison of While Loop code in PHP VS C++

PHP CodeSame code in C++
  $x=1;Int x=1;
                 echo “The value is :$x<br>”;cout <<”The value is :”<<x<<endl;

Examples of While loop in PHP

PHP Program to print the numbers in reverse order by asking the user to input a number

|||| Click to read Complex programs of numbers in reverse order (not for beginners) ||||

Subscribe for Friendship

Latest posts by Prof. Fazal Rehman Shamil (see all)

Buy advertisement space on T4Tutorials

For more details email [email protected]