background
|
|
Computer

Computer
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
PHP from the Ground Up

Page 10 — Loop-dee-Loops

Loops are really handy. They let you program your code to repeat itself (and also to figure out how many times to run through itself before it's done). Loops have instructions to "keep running this piece of code over and over again until certain conditions are met." You can use more than one kind of loop. Let's look at the most basic kind, the "while" loop.

The while loop says,

while (something is true)

{

// do something that you specify

}

While loops are often used with incrementing and decrementing a variable that is an integer. What in the hell does that mean? It means that you can automatically have the script add (or subtract) a whole number (1, 2, 3, etc.) from part of a script each time it runs through, until the number reaches a maximum or minimum value that you've set.

So if you wanted a script to print the numbers from 1 to 10, you can tell it (this is English, not PHP here):

a. the variable $MyNumber = 1;

b. print $MyNumber;

c. add 1 to $MyNumber;

d. go to sep a. and run this script again with the new value of $MyNumber;

d. stop when $MyNumber reaches 11;

The syntax for incrementing and decrementing the value of a variable is:

$a++;

adds 1 to the value of the variable $a each time through

$a--; subtracts 1 from the value of the variable $a each time through

So the code itself for printing the numbers 1 through 10 could look like this:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
<?php

$MyNumber = 1;

while ($MyNumber <= 10)

{

print ("$MyNumber");

$MyNumber++;

}

?>

line 1: start PHP code;
line 3: set variable $MyNumber to 1;
line 5: initiate "while" loop: while the variable $MyNumber is less than or equal to 10, execute what's below; otherwise move on;
line 9: print the current value of $MyNumber;
line 11: add 1 to the value of $MyNumber;
line 15: end PHP code.

To see what all this does, check out the results of the code above.

For these loops, you can use all the "operators" listed on page 9 to be the conditions that must be met before the loop stops.

Other Loops

PHP has other kinds of loops, but they are beyond the scope of this tutorial. If you want to learn what they are and how to use them, follow these links to PHP.net:

next page»