PHP While Loop

by Hiroshi on June 21, 2008

in Loops, PHP Basics, 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
 
?>

Related Posts

Previous post:

Next post: