The early part of this article will focus on both basic and advanced WHILE looping techniques entirely written for PHP. The last part will be devoted to the use of WHILE Loop in displaying MySQL queries. There are different types of loops in PHP that suit different applications. Seeing actual examples and real applications will enable a developer to use this information to determine which loop script is similar to his intended application; thus, he can use it to write derivative programs. This marks the first step towards mastery in writing loop statements in PHP/MySQL. If you are interested, keep reading. Basics: Loop to output increasing or decreasing sequence of numbers This is basic; a lot of applications depend on outputting an increasing or decreasing sequence of numbers. See the examples below: Example #1: Output numbers from 1 to 10 in HTML <?php $i=1; while ($i<=10) { echo $i++; echo '<br />'; } ?> What if you need to produce numbers starting from 51 and continuing to 202? All you need to do is customize using the format (bold): <?php $i=51; while ($i<=202) { echo $i++; echo '<br />'; } ?> Example #2: Output a decreasing sequence of numbers: 10 to 1 in HTML A variation of this can be formulated but using $i— <?php $i=10; while ($i>=1) { echo $i--; echo '<br />'; } ?> The situation is somewhat reversed from what is shown in Example 1. Example #3: Output even numbers in HTML: We even use $i++ to produce even numbers; see below. The code will produce an even number of 2, 4, 6, 8, 10.Instead of using 10 as the last number, 8 is used, since the loop will add twice. <?php $i=0; while ($i<=8) { $i=($i++)+2; echo $i; echo '<br />'; } ?> The same principle applies to outputting odd numbers or any type of number sequences.
blog comments powered by Disqus |
|
|
|
|
|
|
|