One of the most popular applications for WHILE loops is acting as a COUNTER. For example, say we want to generate 36 random numbers between 101 and 300. We will use a WHILE loop to count looping events until we've completed 36 of them. This function is used as a random number function: echo mt_rand(101, 300). And we will use this basic loop as a counter: <?php $i=1; while ($i<=36) { echo $i++; echo '<br />'; } ?> Combine the random number generator function with a WHILE loop counter and we get: <?php $i=1; while ($i<=30) { echo mt_rand(101, 300); $i++; echo '<br />'; } ?> Note that $i++ is not being output to HTML because it is only used as a counter. To label the generated random numbers in the form like this: 1.) 105 2.) 230 3.) 165 We will echo the “counter” beside the generated random number: <?php $i=1; while ($i<=30) { echo $i++.'.)'.' '.mt_rand(101, 300); echo '<br />'; } ?>
blog comments powered by Disqus |
|
|
|
|
|
|
|