PHP Magic Book – Free PHP Scripts, Tutorials and Downloads, PHP AtoZ Reloaded, free php tutorials, free php downloads, php scripts, PHP tips

PHP While Loop

The while keyword takes a condition in parentheses, and the code block that follows is repeated while that condition is true. If the condition is false initially, the code block will not be repeated at all.

The repeating code must perform some action that affects the condition in such a way that the loop condition will eventually no longer be met; otherwise, the loop will repeat forever. Such loops are Infinite Loops.

Structure Of PHP While Loop

- Define
- Condition
- Print
- Increment or decrement

while ( conditional statement is true)
{
	//do the task;
}

PHP While Loop Example

<?php
$num = 3;
while($num < 10)
{
echo $num;
$num = $num + 1;
$num++;
}
 
// Output: 3579
 
?>
<?php
$count = 1;
while ($count <= 10) {
  $square = $count * $count;
  echo "$count squared is $square <br />";
  $count++;
}
 
// Output:
// 1 squared is 1
// 2 squared is 4
// 3 squared is 9
// 4 squared is 16
// 5 squared is 25
// 6 squared is 36
// 7 squared is 49
// 8 squared is 64
// 9 squared is 81
// 10 squared is 100
 
?>
  • Share/Bookmark
Tags: , ,
Posted in: Loops, PHP Basics, While Loop
Post's RSS » RSS 2.0
Post's Comments RSS » RSS 2.0

Related Posts




  1. 1 Trackback(s)

  2. Sep 7, 2008: Blue Box Sols » Blog Archive » PHP Do While Loop

Post a Comment

  Subscribe Via RSS
  Subscribe Via Email