Home arrow PHP arrow Page 2 - Mastering WHILE Loops for PHP and MySQL

Using WHILE Loops as Counters - PHP

Do you want to learn how to handle PHP WHILE loops? WHILE loops are one of the most powerful features as well as the easiest loop available to any PHP/MySQL developer. They enable us to shorten repetitive tasks for a highly useful application. This tutorial gives examples of WHILE loops in PHP/MySQL that beginner and novice developers can use as a quick reference for building similar loops in their applications.

TABLE OF CONTENTS:
  1. Mastering WHILE Loops for PHP and MySQL
  2. Using WHILE Loops as Counters
  3. Generating Unique Random Numbers Using WHILE Loops
  4. Constructing Trigonometric Tables Using WHILE Loops
  5. Retrieving All Rows in a MySQL Table Using WHILE Loops
By: Codex-M
Rating: starstarstarstarstar / 9
October 27, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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++.'.)'.'&nbsp;'.mt_rand(101, 300);

echo '<br />';

}

?>



 
 
>>> More PHP Articles          >>> More By Codex-M
 

blog comments powered by Disqus
   

PHP ARTICLES

- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 8 - Follow our Sitemap

Dev Shed Tutorial Topics: