I will present some of the most important building blocks that any programming language has : loops. Even if you are coding in C, Java or PHP you will use them almost on a daily basis. This series of tutorials are as until now for beginners, so I think intermediate or advanced users will be bored.
I will start showing FOR Loop.
The code above makes the sum of 1 with 20. This of course can be done with a mathematical formula but the purpose was to show how FOR is working. It gives to $i the value 1, 2, 3, and so on until 20. In { } we give to $sum the value of $sum + $i; that makes our sum. We must initialize for safety reasons $sum with 0.
Now let’s assume that we have some entries in a database. For example in a shopping cart you add products and you want to display them. When you have to deal with array’s you can use ForEach Loop.
We have three products declared in $v and their prices in $v2. I will make some tutorials later about MySQL and working with databases. We take each value from $v in $value and we are printing it. Then I initialize the $sum with 0, so that I can make the $sum in the next foreach loop.
The loops presented above are perfect if we know the termination condition. We go exactly on three products.
But if we need to test a condition for our loop to continue do while and while do comes in handy.
In the example above I give to $i the value 1000. Then I check if $i divides to 2 exactly. If yes then in the while loop will divide to 10. For example if I don’t divide by 10, then it will be a infinite condition as $i will always divide to 2 without any remainder.
Do … While:
The output of this is : 101 102 103 104. So we can observe easily that even if $i <= 103 the loops executes one more time. So if we are to compare the last two loops we must say that the first one can be never executed if the condition is false from the beginning, when the second one, do-while loop executes at least once.
Leave a Reply