PHP Control Structures - Loops
(Page 2 of 2 )
Alright, time for loops! Whenever you want something done over and over, loops are the control structures of choice. One example for using loops is reading line by line from a text file. So first I'll just show you the simplest loop there is: while!
While loops<?php $myvariable = 0; while ($myvariable < 10) { print "HELLO!"; $myvariable++; } ?> |
This one means "as long as $myvariable is smaller than ten, print out 'HELLO!' and add one to $myvariable". So this example will print out "HELLO!" ten times. If we'd set $myvariable to ten before the while loop, it would not have printed out anything. But what if we want PHP to print out at least one "HELLO!" in any case? Check this:
Do Loops<?php $myvariable = 10; do { print "HELLO!"; $myvariable++; } while ($myvariable < 10); ?> |
Can you see the difference? If you use a do loop, the condition (in this case "$myvariable < 10") is checked AFTER the code within the loop has been processed once! So in the above example, you will see one "HELLO!". Ready to look at a more complex loop? OK, here we go!
For loopsLet's use the "HELLO!" example again:
<?php for ($countervariable = 0; $countervariable < 10; $countervariable++) { print "Hello!"; } ?> |
Can you imagine what happens inside the parentheses? Right, PHP initializes $countervariable and gives it the value zero. Then it starts looping. With each loop, it is checked whether $countervariable is smaller than ten and if that is true, "HELLO!" is printed and $countervariable is increased by one! Whenever you know how many loop cycles you need, it's best to use a for loop.
OK, that's it. These are the most important control structures in PHP.
Thanks for reading and - see you next time!
About the AuthorBenjamin Bischoff (a.k.a. "laxersaz" on codewalkers.com) is a 24-year-old programmer for M&R Medienkonzepte und Realisation GmbH in Cologne, Germany who is working with different languages like HTML, JavaScript, ActionScript, Lasso and, of course, PHP - his favorite. He has been writing programs for almost 10 years and, among other things, created a very successful multiplayer online game together with a friend (www.sumo-eier.de - in German). He can be reached at laxersaz@web.de.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |