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
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- 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...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: