PHP Loop While
PHP Tutorial » PHP Loops While
In this chapter you will learn how to repeat the code using loops in PHP.
PHP loop
Often, when writing code, you want the same block of code to be run multiple times, a certain number of times. So instead of adding more or less nearly identical lines of code to a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
In PHP, we have the following types of loop:
while - loop a block of code as long as the specified condition is true
do ... while - execute the command once, then repeat the loop as long as the specified condition is true
for - loops through a block of code a specified number
foreach - loops through a block of code for each element in an array
PHP while - loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (state is true) {
code to execute;
}
PHP while - loop example
Example 1: The example below shows numbers from 1 to 5:
<?php
$x = 1;
while($x <=5) {
echo "The number is: $x <br>";
$x++;
}
?>
$x = 1;
while($x <=5) {
echo "The number is: $x <br>";
$x++;
}
?>
Example explained:
$x = 1; - Initialize the loop counter ($ x) and set the start value to 1
$x <= 5 - Continue the loop as long as x is less than or equal to 5
$x ++; - Increase the value of the loop counter by 1 for each iteration
While Loop
Another example shows up to 100 with tens:
Example 2:
<?php
$x =0;
while($x <= 100) {
echo "The number is: $x <br>";
$x+=10;
}
?>
$x =0;
while($x <= 100) {
echo "The number is: $x <br>";
$x+=10;
}
?>
PHP While Loops
PHP While Loops. Tutorial While Loop - php tutorial
Online Editor
This tool makes it easy to create, adjust, and experiment with custom colors for the web.
HTML Templates

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.
CSS HTML Layout

Find here examples of creative and unique website layouts.
Free CSS HTML Menu

Find here examples of creative and unique website CSS HTML menu.