How to do PHP While Loops
Now that you know how to use if then statements lets move on to a basic loop.
- Lets get started by opening your favorite editor and starting a fresh source page. Start off with the basic coding which denotes a php area. <?php ?>
- Now lets add in a variable and an echo statement. Give one variable a value of 0 then echo it.
<?php
$x=0;
echo $x;
?>
This should print out 0.
PHP generally starts many constructs at 0, not at 1 so its generally better to start counting from 0 in programming..
- Now lets add in a basic loop. The while statement is very similar to an if statement except a while loop will do the things as long as its conditions are met (or until timeout which is generally 3-5 minutes depending on your server settings).
<?php
while (/*requirements*/)
{
//Stuff to do
}
?>
This won’t print anything yet
- Now lets make that actually do something. We’ll have it run 5 times, so while $x<5 do something. Of course we have to increase $x inside the loop otherwise it won’t end. So the only action we have right now is adding one to $x, we can do this with $x=$x+1; or in english x is equal to x +1.
<?php
$x=0;
while ($x<5)
{
$x=$x+1;
}
?>
This won’t print anything yet
- Now lets add on an echo so we can see the progress of $x counting up towards 5.
<?php
$x=0;
while ($x<5)
{
echo $x;
$x=$x+1;
}
?>
This should print out “12345“
- Ok now there is a better way to add one to $x and thats a special operation which is coded like this ++$x;
- Now lets add some text to each echo so it looks a bit nicer. You can print a variable and letters by using an echo with quotes. so in this statement echo “x: $x”; the first x will simply be the letter x and the second one which is preceded by a $ will be the variable.
<?php
$x=0;
while ($x<5)
{
echo "x=$x";
++$x;
}
?>
This should print out “x: 1x: 2x: 3x: 4x: 5”
Now this doesn’t look much nicer (actually it looks worse!), but we’ll fix that in the next step. - A PHP echo will place code directly into the html of a file. So if you type html code into the echo you can use different html functions to change displays. In this way you can make things bold, manipulate css styles etc. For now we’ll just add a <br> to the end of each line this will make the numbers go to different lines.
<?php
$x=0;
while ($x<5)
{
echo "x=$x<br>";
++$x;
}
?>
This should print out:
x: 1
x: 2
x: 3
x: 4
x: 5
