Type Here to Get Search Results !

Lesson 5: Loops

In PHP, it is possible to manage the execution of scripts with different control structures. In this lesson, we will look at loops. Loops can be used to repeat parts of a script a specified number of times or until a certain condition is met.

"while" loops

The syntax for a documentationwhile loop is:



The syntax can almost be directly translated into English: do something while a condition is met.
Let's look at a simple example:


show example 

In the example, a variable named "$x" is used. As you can see, variables in PHP always start with a "$" character. It's easy to forget this at first, but it's absolutely necessary to remember or else the script doesn't work.

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 documentationfor on the form:



The statement is repeated as long as 'Initialization' + 'Step' meets the 'Condition'. If that doesn't make sense, look at this example:


show example 

In the example above, $x is growing with the value 5 in each loop. The loop will continue as long as $x is below or equals 50. Also note how the value $x is used as part of the sentence.

Here is another example:


show example 

Do you get it? First we set the value of $x to 1. Then in each loop, we write a heading at level $x (h1, h2, h3, etc.) until $x is equal to six.

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.


show example 

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>.

Loops becomes more useful when you've learned a little more. When you understand the principle in a loop, you can proceed to the next lesson, where we look at conditions.

Post a Comment

0 Comments