PHP Learn It! PHP While Loop
"Best Deal"

"Bored - Do You Agree?"
t-shirtgirlspics

Bored - Studied Hard - Enjoy Yourself "TAKE A BREAK"

"Decide Now-So Many Choices"
"Amazing Deals"
Once You Know, You Newegg

PHP While Loops

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.

Learn PHP and MySQL fast!

Learn how you can start building rich interactive database driven sites like a professional developer easily and quickly...

>> Order your copy now for just $39.95 <<

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

Build large scalable dynamic websites using PHP yourself
Learn PHP like a pro >>

<< PHP For Loop Top PHP Functions >>