PHP Tutorial – The while loop

A loop is a block of code that enables you to repeat the same set of statements or commands over and over again; the actual number of repetitions may be dependent on a number you specify.

The while loop

The while loop will continue to execute a block of code as long as the specified condition is true and if the condition becomes false the code within the loop will not be executed.

Syntax:

while (condition)
{
code to be executed;
}

Example:

<?php
$num=1;
while($num<=10)
{
echo "The number is " . $num . "<br />";
$num++;
}
?>

Result:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

In our example we have initialize our $num variable into 1 and the condition is while our $num variable is less than or equal to ten, it will write some output and the loop will continue and it will increase by 1 as the loop runs.

, , , , , ,

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.