Loops

Sometimes, while designing a program, you need to execute a set of statements repeatedly. You might need to display an entire set of data with hundreds of elements or list all numbers from 1 to 100. Fortunately, PHP offers loops, which allow you to execute a set of statements as many times as needed. There are several different types of loops. Each type has strengths and weaknesses. You most often find loops with arrays, which I go over in Chapter 10.

while

Let’s start off with the most common loop: while. Using the while loop, you execute the statements as long as a certain condition is true. Remember the three stages of the while loop:

  • Initialization outside the loop, which ensures the loop executes at least once

  • Condition inside the while statement

  • Code inside the loop, which causes it to end

Let’s look at the structure:

while (condition is true)
{
    //execute repeated statements
} //end of loop

You can enter whatever statements you want executed.

Caution

Be careful--you don’t want to accidentally create a loop that is always true. If the statement inside the condition test is never false, the loop will execute forever. This could occur if you write something like while (1==1) or even while(1), because any non-zero number is always considered true. A common error is to check some condition that never occurs, such as while ($x!=7), when the variable $x never actually becomes 7. If you do this, the loop continues forever and the page never loads correctly.


Let’s create a simple program: a counter that counts from 1 to 10 and then displays the digits on the screen. This file is phpft07-05.php on the CD and results in a page that looks like Figure 7.8.

Figure 7.8. The phpft07-05.php file.


<html>
<head>
<title>A counter from 1 to 10 using while</title>
</head>

<body>

<?php

//give starting value to counter
$counter=1;

//increment counter from 1 to 10
while ($counter<=10)
{
   echo "$counter<br />";
   $counter++;
}

?>
</body>
</html>

As you can see, this program displays the numbers 1 through 10 on new lines. This program uses the ++ operator to increase the variable each time the loop goes through. Notice that I created the variable before the loop began. If I had done this inside the loop, the $counter variable would continually be set to 1 at the beginning of each iteration of the loop.

for

The for loop is very similar to while, except that you do not need to create or increase the variable outside of the main loop statement: Everything is done inside the beginning statement of the for loop. They are optimized for counting situations in which you know exactly how many times you want to execute some code. Instead, you actually define the variable and increment it. Let’s look at the for loop structure:

for (variable assignment; comparison test; variable change)
{
//execute statements
}

Doesn’t look too bad, huh? Put the loop in a program. We will create an HTML form that lets the user enter any two numbers. As long as the second number is larger than the first, the PHP page will display all numbers from the first to the second number. Let’s take a look at the source. The first page is for the HTML document:

<html>

<head>
<title>Counter of two arbitrary numbers</title>
</head>

<body>
<form name="numbers" method="get" action="phpft07-06.php">
<p>
Enter your first value:
<input type="text" name="first" />
<p>
Enter your second value:
<input type="text" name="second" />
<p>
<input type="submit" >
</form>

</body>

</html>

As you can see here, all we have to do is create two textboxes that contain numbers. Figure 7.9 shows what the page looks like.

Figure 7.9. The phpft07-06.html file.


The next page is the PHP code:

<html>
<head>
<title>Arbitrary Counter</title>
</head>

<body>
<?php

//Store variables
$a = $_GET['first'];
$b = $_GET['second'];

//if b is greater than a, loop through everything from a to b
if ($b > $a)
{

    for ($i = $a; $i <= $b; $i++)
    {

        echo "$i<br />";
    }
}
//b must be greater than a! Error if not.
else
{
    echo "Your second number is not greater than your first number. Please enter in
      new numbers.";

}
?>

</body>
</html>

This page initially tests to see if the second number is larger than the first. If this is true, it creates a for loop that counts through all of the numbers and displays them, one after another. If this is false, it simply echoes out an error statement. Figure 7.10 shows what this page looks like with the first value being 4 and the second being 16.

Figure 7.10. The phpft07-06.php file.


do...while

The do...while loop is almost identical to the regular while loop except for one thing: This loop always executes at least once—even if the condition is false. Let’s look at the structure:

do
{
//execute statements
} while (condition is true);

For example, if we were using while, what would happen if we wrote the following code?

$x = 10;
while($x < 10)
{
echo $x;
}

This will obviously do nothing, because $x starts off at 10. The while condition is never true and the echo statements never execute. What if we use a do...while loop, however?

$x = 10;
do
{
echo $x;
} while ($x < 10);

This code would simply display a counter from 1 to 10.

Note

foreach is a specialized type of loop that only works with arrays, so I go over it in Chapter 10.


break and continue

There are two rare commands that deal with loops: break and continue. You might remember break from the switch statement: When using it, the switch command finished and exited. The same thing happens within loops. break causes a loop to break out of the loop immediately. continue, on the other hand, immediately forces the loop to go back to the top and execute from the beginning, skipping the rest of the loop for that individual iteration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.53.209