PHP While loop with 2 examples

Introduction to While loop of PHP

The While loop is used to execute a block of code until the given condition is true. The condition check is similar to the one used in the PHP if statement to check if the condition is true or false.

See an example of while loop

In While PHP loop, after the code has been executed, the conditional statement will again be evaluated and the loop will continue until the given expression is found to be false.

The while loop Structure

Following is the general structure of PHP While loop:

 while ( condition ){

//block of code here;

Increment;

}

Example of While loop

The following example shows using the While loop. The variable i is initiated with the value 0 and then incremented after executing statements by 1. The loop will go on until the value of i reaches 5.

PHP while loop

Experience this example online



While loop example with HTML

Following example uses the HTML table and fills with data based on While loop.

The output of the above code will be a table filled with Quantity and price as the while loops through the variable i.

PHP while loop html

Experience this example online



The PHP do while loop also works alike except the do while loop will execute the code at least once and then meet the condition. For more on do while and other loops visit the dedicated chapters by the links given below.

Other Loops:  For Loop | Do While Loop | Foreach Loop

Was this article helpful?

Related Articles

Leave A Comment?