Monday, April 13, 2015

PHP-Loop

PHP Loops

When you write code, we want the same block of code to run over and over in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
  • while – repeat through a block of code as long as the specified condition is true
  • do...while - repeat through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - repeat through a block of code a specified number of times
  • foreach - repeat through a block of code for each element in an array

 

while Loop


The ex. shows first sets a variable $y to 1. Then, the while loop will continue to run upto $y is less than, or equal to 4 ($y <= 4). $y will increase by 1 every time the loop runs ($y++):
Example:
<?php 
$y = 1;
 

while($y <= 4) {
    echo "The number is: $4 <br>";
    $x++;
}
 
?>
o/p:

The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 



Do_while Loop:


 Same as while just execution of condition after do part means, after a block of code.


<?php
$y = 1;

do {
    echo "The number is: $y <br>";
    $y++;
} while ($y <= 5);

?>

o/p:

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

if you want in certain case, your code to be executed once either condition is true or false then, do while loop is the way to use. 
in following example shows such condition,

<?php 
$a = 7;

do {
    echo "The number is: $a <br>";
    $a++;
} while ($a<=6);
?

O/P:
The number is: 7 

even if condition is false but, value of $a=7 has been printed once.

No comments:

Post a Comment