// Tutorials / While and For Loops in PHP

Posted The: 31/05/2008 - AT: 6:30

Edited The: 20/10/2008 - AT: 19:24

The easiest loop to use in PHP, is the While loop. For instance loops can be useful when displaying your links Dymanicly, or even displaying the comments for the articles. Creating Sitemaps, or RSS Feeds. In short, it saves you from a lot of work.

While Loop Example:

The below will continiue for as long as $number is equal to 1.

The while loop syntax is: while (condition) {DoStuff}

It will check to see if the condition is met, at the beginning of each run.

<?php
$number = '1';

while ($number = '1') {
echo 'Repeating this Forever';
}

?>

Lets limit the loop to a maximum of 15 runs.

<?php
$number = '1';

while ($number <= '15') {
echo 'Run Number:' . $number . "\n";

++$number;
}
?>

The conditions basically says, for as long as $number being less then, or equal to 15, run the loop. The last part ++$number;, will add 1 to $number at the end of each run.

Be sure not to make below mistake:

<?php


while ($number <= '15') {
$number = '1';
echo 'Repeating this Forever' . "\n";

++$number;
}
?>

Since it will reset $number each time the loop has executed. Also make sure not to declare variables inside the loop unless its nessesery, since doing so will re-declare them each time the loop is executed, and as such slow down your scripts.

For Loop Example:

For loops are difficult for many beginners to learn, one reason might be the "for" which apears confusing. So i ask that you keep in mind the While Loop Example from before, then you will have an easier time understanding the next example.

<?php
for ($number = '1'; $number <= '15'; ++$number) {
    echo 'Run Number:' . $number . "\n";
}
?>

I have highlighted the important parts in red, remember the order from the while example now.

The for loop actually uses the same order. However instead of declaring $number before the Loop, and adding 1 to $number inside the "actions list", we simply include those actions in the syntax of the loop.

The for loop Syntax is: for (expr1; expr2; expr3) { DoStuff }

Expr1 is where i declared $number, expr2 can be translated into the "condition" from the while loop, and finally expr3 is the action to be performed after each run, in this case, the addition to $number.

Stumble It!

Author: BlueBoden

Comments: [0]

  1. HTML Tutorial
  2. CSS Tutorial
  3. XHTML Tutorial
  4. RSS Tutorial
  5. PHP Tutorial
  6. htaccess Tutorial
  7. Server Tutorial
  8. SEO Tutorial

Checked At:03:01

6 Guests

0 Users

Online doing the past 15 Minutes!

PageRanking.dk - Flere hits og højere PageRank - GRATIS tilmelding!

This page was created in 0.141623020172 seconds

Welcome Guest