Posted by : senan Wednesday, February 12, 2014

Welcome! In this section we going to cover the use of while loops in PHP.

While Loops

Just like the for loop, while loop is used to execute a block of code for certain number of times until the condition in the while evaluate to true.

While Loop Syntax
while(condition)
{
 //execute block of code
}
Note: The condition statement must evaluate to true for the loop to exit otherwise the loop will run forever.

PHP While Loop

Example - Print number through 1 to 5 with PHP While Loop

Example below prints integers through 1 to 5
<?php

$i = 1;
while ($i <= 5 )
{
 echo $i . "<br>";

 $i = $i + 1;
}

?>
In the above example, you see that the loop is run until the value of $i is less than or equal to 5 according to the condition in the loop. The $i = $i + 1; statement increments the value of $i by 1 on each iteration of our while loop.

Example - Print decimal number through 1.0 to 5.0 with PHP While Loop

Here is another example with decimal numbers.
Example below prints decimal numbers through 1.0 to 5.0
<?php

$i = 1.0;
while ($i <= 5.0 )
{
 printf("%.1f<br>", $i);

 $i = $i + 1.0;
}

?>
Breaking out of a PHP Loop
We can use the break; statement to stop the loop from executing.
Sometimes when we are working with loops, we want to break the loop when a certain condition is true.
For example, we might want to break our loop when $i reaches 4. Lets look at the example below.
<?php

$i = 1;
while ($i <= 5 )
{
 if($i == 4)
  break;

 echo $i . "<br>";

 $i = $i + 1;
}

?>
In the above example, we break the loop when $i reaches 4. The loop outputs...
1
2
3

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Learning Programming Language - Skyblue - Powered by Blogger - Designed by Johanes Djogan -