Loops
Like any other language, loop in PHP is used to execute a statement multiple times until and unless a specific condition is met. This helps the programmer to save both time and effort of writing the same code multiple times.
For Loop
This type of loops is used when the programmer knows in advance, how many times the block needs to execute.These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.
Basic Structure for loop
for(intialization; condition; Increment or Decrement)
{
statement;
}
Progrram Excution With For Loop
Problem: Square from 1 to 15 every number
//For loop Progrram
for($x=1;$x<=15;$x++)
{
echo "The square value of"." ".$x." "."is"." ".($x*$x)."<br/>";
}
Task: You should try, Find out 1 to 15 prime number and calulate their square value
Fetch For Loop With Array
//Fetch for loop with array
$arrayVariable=array(0,2,3,4,5,6,7,8,9,1);
for($i=0;$i<=9;$i++){
// echo "Array value is"." ".$arrayVariable[$i]."<br/>";
echo "<pre>";
var_dump($arrayVariable[$i]);
echo "<pre/>";
}
While Loop
The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the statements, and goes on executing it as long as the condition until true
Basic Structure while loop
intializing;
while(condition){
statement;
increment or decrement;
}
Progrram Excution With while Loop
//while loop progrram
$j=0;
while($j<=5){
echo "The value of j is"."=".$j."<br/>";
$j++;
}
Fetch while Loop With Array
//Fetch array with while loop
$arrayVariable=array(0,2,3,4,5,6,7,8,9,1);
$i=0;
while($i<=9)
{
echo $arrayVariable[$i]."<br/>";
$i++;
}
Do While loop
This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do…while loop. After executing once, the program is executed as long as the condition until true.
Basic Structure do while loop
intializing;
do{
statement;
increment or Decrement;
}
while(condition);
Progrram Excution With do while Loop
//Progrram with do while loop
$i=0;
do{
echo $i."<br/>";
$i++;
}
while($i<=6);
Fetch do while Loop With Array
//Fetch do while loop with array
$arrayVariable=array("Karim","Rahim","Jaber","Tina","Mina","Raju","Rahman");
$i=0;
do{
echo $arrayVariable[$i]."<br/>";
$i++;
}
while($i<=7);