Site icon T4Tutorials.com

While Loop in PHP

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. 

Figure: while loop in PHP.

Example of While loop in PHP.

An example program to demonstrate the while loop.

<?php

  $x=1;

 while($x<=10)

 {

                 echo "The value is :$x<br>";

                 $x++;

 }

?>

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

Code

Explanation

<?php PHP  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 Code Same code in C++
<?php
  $x=1; Int x=1;
 while($x<=10) While(x<=10)
 {
                 echo “The value is :$x<br>”; cout <<”The value is :”<<x<<endl;
                 $x++;
x++;
 }
?>

Examples of While loop in PHP

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

<?php

$number=123;
$orignal_num=$number;
$rs=0;
while($number>0)
{
$rs = $rs * 10 + $number % 10;
$number = (int)($number / 10);

}
print_r("Result:$orignal_num<br>Revrse of Number is= $rs");

?>

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

Exit mobile version