PHP

While loop: (Php tutorials:part-6)

Written by Saiful Islam

Usage of while loop:

While loop (loops are the sequence of tasks in programming) is used to execute a continuous program until the condition become false. When we need to command for a task to run again and again then we can simply use the While loop. So, we don’t need to write a command again and again if we use this loop.

Structure:

while(condition)
{
Commands;
}

Example: 1

Have only commanded for showing the text for 10 times.

Input

Ouput

<?php

$x=1;

While($x<=10)

{

echo “Welcome to TechFanz.com<br>”;

$x++;

}
?>

 while loop using php

 

Description:
1. The value of variable x is equal to 1.

2. The while loop will execute the program till the value of x remains smaller than 10 or equal to 10.

3. The command for showing the text “Welcome to Tech-info24.com” will be executed until the condition x≤10 is true.

  1. At the 6th line I have written $x++ so that the value of x increases gradually. The value of x will rise by 1 after ending the program within the while loop. That means after executing the first loop the value of x will be 2. And thus it will be 3, 4, 5, 6, 7, 8, 9, 10, 11 accordingly. But it will stop working when it will cross the limit between 1 to 10.
  2. For each true condition the echo will be executed for once.

 

Example: 2

Here I have used both the text and variables:

Input

Ouput

<?php

$x=0;

echo “Let’s count 0 to 9”;

While($x<10)

{

echo “<br>”.$x;

$x++;

}

?>

 while loop for numbers using php

 

Note:

  1. I didn’t keep the first echo statement within the while loop because I didn’t want to show it again and again. I only used the 2nd echo statement within the while loop for showing only the numbers between 0 to 9.
  2. If we want to decrease the value of x gradually then we have to write X– instead of X++.

About the author

Saiful Islam

Leave a Comment