Tutorials

PHP for beginners -Lesson 6

Sending
User Rating 5 (1 vote)

WHILE LOOP IN PHP
 
Code will execute continue till condition reached false.
Syntax:
initialization – set your counter above while loop while (condition)
  {
  code here…
   
  increment/decrement
  }
 
Parameters :  
  condition – Loop will continue till condition is TRUE.
  increment/decrement – increase or decrease your counter , this parameter should be before end of loop.  

  Example 1 : Display 1 to 10 numbers using While loop. <?php
    $i=1;
    while($i <= 10){
        echo $i."\t";  // \t use for TAB
        $i++;
    }
?>
Output:
1 2 3 4 5 6 7 8 9 10

DO-WHILE LOOP IN PHP
 
Syntax :   do{
    statement1;
    statement2;
    statement3;
    
    increment/decrement;
 
}while(condition);
Do-while loop continue until condition become false;

Example 2 : Display 1 to 10 numbers using Do-While loop. <?php
    $i=1;
    do{
        echo $i."\t";  // \t use for TAB
        $i++;
    }while($i <= 10);
?>
Output:
1 2 3 4 5 6 7 8 9 10
 
Note : The only one technical difference between WHILE and DO-WHILE loop is D0-WHLE loop will execute at least once without checking condition.
 
In my last tutorial, I have given solution of below program list using For loop….
a) Display table of input number
b) Fibonacci series
c) Prime number from 1 to 100
 
Can you try above list of program using WHILE & DO-WHILE LOOP?

Share your Thoughts