- Before You Begin: Accessing PHP
- Creating a Sample Application: Bob's Auto Parts
- Embedding PHP in HTML
- Adding Dynamic Content
- Accessing Form Variables
- Understanding Identifiers
- Examining Variable Types
- Declaring and Using Constants
- Understanding Variable Scope
- Using Operators
- Working Out the Form Totals
- Understanding Precedence and Associativity
- Using Variable Handling Functions
- Making Decisions with Conditionals
- Repeating Actions Through Iteration
- Breaking Out of a Control Structure or Script
- Employing Alternative Control Structure Syntax
- Using declare
- Next
Repeating Actions Through Iteration
One thing that computers have always been very good at is automating repetitive tasks. If you need something done the same way a number of times, you can use a loop to repeat some parts of your program.
Bob wants a table displaying the freight cost that will be added to a customer’s order. With the courier Bob uses, the cost of freight depends on the distance the parcel is being shipped. This cost can be worked out with a simple formula.
You want the freight table to resemble the table in Figure 1.7.
Figure 1.7 This table shows the cost of freight as distance increases
Listing 1.2 shows the HTML that displays this table. You can see that it is long and repetitive.
Listing 1.2 freight.html—HTML for Bob’s Freight Table
<!DOCTYPE html>
<html>
<head>
<title>Bob's Auto Parts - Freight Costs</title>
</head>
<body>
<table style="border: 0px; padding: 3px">
<tr>
<td style="background: #cccccc; text-align: center;">Distance</td>
<td style="background: #cccccc; text-align: center;">Cost</td>
</tr>
<tr>
<td style="text-align: right;">50</td>
<td style="text-align: right;">5</td>
</tr>
<tr>
<td style="text-align: right;">100</td>
<td style="text-align: right;">10</td>
</tr>
<tr>
<td style="text-align: right;">150</td>
<td style="text-align: right;">15</td>
</tr>
<tr>
<td style="text-align: right;">200</td>
<td style="text-align: right;">20</td>
</tr>
<tr>
<td style="text-align: right;">250</td>
<td style="text-align: right;">25</td>
</tr>
</table>
</body>
</html>
Rather than requiring an easily bored human—who must be paid for his time—to type the HTML, having a cheap and tireless computer do it would be helpful.
Loop statements tell PHP to execute a statement or block repeatedly.
while Loops
The simplest kind of loop in PHP is the while loop. Like an if statement, it relies on a condition. The difference between a while loop and an if statement is that an if statement executes the code that follows it only once if the condition is true. A while loop executes the block repeatedly for as long as the condition is true.
You generally use a while loop when you don’t know how many iterations will be required to make the condition true. If you require a fixed number of iterations, consider using a for loop.
The basic structure of a while loop is
while( condition ) expression;
The following while loop will display the numbers from 1 to 5:
$num = 1;
while ($num <= 5 ){
echo $num."<br />";
$num++;
}
At the beginning of each iteration, the condition is tested. If the condition is false, the block will not be executed and the loop will end. The next statement after the loop will then be executed.
You can use a while loop to do something more useful, such as display the repetitive freight table in Figure 1.7. Listing 1.3 uses a while loop to generate the freight table.
Listing 1.3 freight.php—Generating Bob’s Freight Table with PHP
<!DOCTYPE html>
<html>
<head>
<title>Bob's Auto Parts - Freight Costs</title>
</head>
<body>
<table style="border: 0px; padding: 3px">
<tr>
<td style="background: #cccccc; text-align: center;">Distance</td>
<td style="background: #cccccc; text-align: center;">Cost</td>
</tr>
<?php
$distance = 50;
while ($distance <= 250) {
echo "<tr>
<td style=\"text-align: right;\">".$distance."</td>
<td style=\"text-align: right;\">".($distance / 10)."</td>
</tr>\n";
$distance += 50;
}
?>
</table>
</body>
</html>
To make the HTML generated by the script readable, you need to include newlines and spaces. As already mentioned, browsers ignore this whitespace, but it is important for human readers. You often need to look at the HTML if your output is not what you were seeking.
In Listing 1.3, you can see \n inside some of the strings. When inside a double-quoted string, this character sequence represents a newline character.
for and foreach Loops
The way that you used the while loops in the preceding section is very common. You set a counter to begin with. Before each iteration, you test the counter in a condition. And at the end of each iteration, you modify the counter.
You can write this style of loop in a more compact form by using a for loop. The basic structure of a for loop is
for( expression1; condition; expression2)
expression3;
expression1 is executed once at the start. Here, you usually set the initial value of a counter.
The condition expression is tested before each iteration. If the expression returns false, iteration stops. Here, you usually test the counter against a limit.
expression2 is executed at the end of each iteration. Here, you usually adjust the value of the counter.
expression3 is executed once per iteration. This expression is usually a block of code and contains the bulk of the loop code.
You can rewrite the while loop example in Listing 1.3 as a for loop. In this case, the PHP code becomes
<?php
for ($distance = 50; $distance <= 250; $distance += 50) {
echo "<tr>
<td style=\"text-align: right;\">".$distance."</td>
<td style=\"text-align: right;\">".($distance / 10)."</td>
</tr>\n";}
?>
Both the while and for versions are functionally identical. The for loop is somewhat more compact, saving two lines.
Both these loop types are equivalent; neither is better or worse than the other. In a given situation, you can use whichever you find more intuitive.
As a side note, you can combine variable variables with a for loop to iterate through a series of repetitive form fields. If, for example, you have form fields with names such as name1, name2, name3, and so on, you can process them like this:
for ($i=1; $i <= $numnames; $i++){
$temp= "name$i";
echo htmlspecialchars($$temp).'<br />'; // or whatever processing you want to do
}
By dynamically creating the names of the variables, you can access each of the fields in turn.
As well as the for loop, there is a foreach loop, designed specifically for use with arrays. We discuss how to use it in Chapter 3.
do...while Loops
The final loop type we describe behaves slightly differently. The general structure of a do...while statement is
do
expression;
while( condition );
A do...while loop differs from a while loop because the condition is tested at the end. This means that in a do...while loop, the statement or block within the loop is always executed at least once.
Even if you consider this example in which the condition will be false at the start and can never become true, the loop will be executed once before checking the condition and ending:
$num = 100;
do{
echo $num."<br />";
}while ($num < 1 ) ;