Lesson 5: Loops
Ak Patel
---
"while" loops
The syntax for a while (condition) {
Statement
}
Let's look at a simple example:
<html> <head> <title>Loops</title> </head> <body> <?php $x = 1; while ($x <= 50) { echo "<p>This text is repeated 50 times</p>"; $x = $x + 1; } ?> </body> </html>
Apart from that, the example is almost self-explanatory. First the variable $x is set to be equal to 1. Then the loop asks the server to repeat the text while $x is less or equal to 50. In each loop, the variable $x will be increased by 1.
"for" loops
Another way to make a loop is with
for (Initialization; Condition; Step) {
Statement
}
<html> <head> <title>Loops</title> </head> <body> <?php for ($x=0; $x<=50; $x=$x+5) { echo '<p>variable $x is now = ' . $x . '</p>'; } ?> </body> </html>
Here is another example:
<html> <head> <title>Loops</title> </head> <body> <?php for ($x=1; $x<=6; $x=$x+1) { echo "<h" . $x . ">Heading level " . $x . "</h" . $x . ">"; } ?> </body> </html>
Loops within loops
In principle, there are no limitations on how loops can be used. For instance, you can easily put loops inside loops and thereby create many repeats.But be careful! PHP becomes slower the more complicated and extensive the scripts. For instance, look at the next example where, with three loops, we can write over 16 million colors!
In order not to make the page slow, we have drastically reduced the number by putting the step to 30 and thereby limited the number of colors to 512.
<html> <head> <title>Loops </title> </head> <body> <?php for ($intRed=0; $intRed<=255; $intRed=$intRed+30) { for ($intGreen=0; $intGreen<=255; $intGreen=$intGreen+30) { for ($intBlue=0; $intBlue<=255; $intBlue=$intBlue+30) { $StrColor = "rgb(" . $intRed . "," . $intGreen . "," . $intBlue . ")"; echo "<span style='color:" . $StrColor . "'>" . $StrColor . "</span>"; } } } ?> </body> </html>
In this example, each of three primary colors (red, green and blue) can have a value between 0 and 255. Any combination of the three colors creates a color on the form rgb(255,255,255). The color code is used as color in a <span>.