Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

The conditional expression in the while statement is enclosed within

parentheses following the keyword while. As long as the conditional

expression evaluates to TRUE, the statement or command block that

follows executes repeatedly. Each repetition of a looping statement

Is called an iteration. When the conditional expression evaluates

to FALSE, the loop ends and the next statement following the while

statement executes.

A while statement keeps repeating until its conditional expression

evaluates to FALSE. To ensure that the while statement ends after

performing the desired tasks, you must include code that tracks the

progress of the loop and changes the value produced by the condi-

tional expression. You can track the progress of a while statement,

or any other loop, with a counter. A counter is a variable that incre-

ments or decrements with each iteration of a loop statement.

The following code shows a simple script that includes a while state-

ment. The script declares a variable named $Count and assigns it an

initial value of 1. The $Count variable is then used in the while state-

ment conditional expression ($Count <= 5). As long as the $Count

variable is less than or equal to 5, the while statement loops. Within

the body of the while statement, the echo statement displays the

value of the $Count variable, then the $Count variable increments by a

value of 1. The while statement loops until the $Count variable incre-

ments to a value of 6.


Repeating Code

$Count = 1;

while ($Count <= 5) {

echo "$Count<br />";

++$Count;

}

echo "<p>You have displayed 5 numbers.</p>";

The preceding code displays the numbers 1 to 5, with each number

representing one iteration of the loop. When the counter reaches 6,

the message “You have displayed 5 numbers.” appears, thus demon-

strating that the loop has ended. Figure 2-5 shows the output of this

simple script.

97

Figure 2-5

Output of a while statement using an increment operator

You can also control the repetitions in a while loop by decrementing

(decreasing the value of ) counter variables. Consider the following

script:

$Count = 10;

while ($Count > 0) {

echo "$Count<br />";

--$Count;

}

echo "<p>We have liftoff.</p>";

In this example, the initial value of the $Count variable is 10, and the

decrement operator (--) is used to decrease the value of the $Count

variable by 1. When the $Count variable is greater than zero, the

statement within the while loop displays the value of the $Count vari-

able. When the value of $Count is equal to zero, the while loop ends,

and the statement immediately following it displays. Figure 2-6 shows

the script output.


CHAPTER 2

Functions and Control Structures

98

Figure 2-6

Output of a while statement using a decrement operator

There are many ways to change the value of a counter variable and to

use a counter variable to control the repetitions of a while loop. The

following example uses the *= assignment operator to multiply the

value of the $Count variable by 2. When the $Count variable reaches a

value of 128 (the first multiple of 2 greater than 100), the while state-

ment ends. Figure 2-7 shows the script output.

$Count = 1;

while ($Count <= 100) {

echo "$Count<br />";

$Count *= 2;

}

Figure 2-7

Output of a while statement using the assignment operator *=


Repeating Code

To ensure that the while statement will eventually end, you must

include code within the body of the while statement that changes

the value of the conditional expression. For example, you may have a

while statement that displays even numbers between 0 and 100. You

need to include code within the body of the while statement that

ends the loop after the last even number (100) displays. If you do not

include code that changes the value used by the conditional expres-

sion, your program will be caught in an infinite loop. In an infinite

loop, a loop statement never ends because its conditional expression

is never FALSE. Consider the following while statement:

$Count = 1;

while ($Count <= 10) {

echo "The number is $Count";

}

99

Although the while statement in the preceding example includes a

conditional expression that checks the value of a $Count variable,

there is no code within the while statement body that changes the

$Count variable value. The $Count variable will continue to have a

value of 1 through each iteration of the loop. This means that the text

string “The number is 1” will be displayed repeatedly until the user

closes the Web browser window.

To modify the DiceRoll.php script to evaluate five rolls using a while

statement:

1.

2.

You can

use the

continue

statement to

halt a looping

statement and restart the

loop with a new iteration.

Return to the DiceRoll.php document in your text editor.

Immediately after the declaration of the $Dice array, declare

and initialize two new variables: $DoublesCount and

$RollNumber.

$DoublesCount = 0;

$RollNumber = 1;

3.

After the new variable declarations, create a while loop by

adding the code shown in bold. Also, revise the echo state-

ment by making the change shown in bold.

while ($RollNumber <= 5) {

$Dice[0] = rand(1,6);

$Dice[1] = rand(1,6);

$Score = $Dice[0] + $Dice[1];

echo "<p>";

echo "The total score for roll $RollNumber was

$Score.<br />";

$Doubles = CheckForDoubles($Dice[0],$Dice[1]);

DisplayScoreText($Score, $Doubles);

echo "</p>";

if ($Doubles)

++$DoublesCount;

++$RollNumber;

} // End of the while loop


CHAPTER 2

Functions and Control Structures

4.

Add the following line after the while loop to display the

number of times doubles were rolled:

echo "<p>Doubles occurred on $DoublesCount of the

five rolls.</p>";

5.

100

6.

Save and upload the DiceRoll.php document.

Open the DiceRoll.php file in your Web browser by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.02/Chapter/DiceRoll.php. Figure 2-8 shows how the

program appears in a Web browser.

Figure 2-8

Output of DiceRoll.php after adding a while statement

7.

Close your Web browser window.

do . . . while Statements

Another PHP looping statement, similar to the while statement, is

the do . . . while statement. The do . . . while statement executes a

statement or statements once, then repeats the execution as long as

a given conditional expression evaluates to TRUE. The syntax for the

do . . . while statement is as follows:

Repeating Code

do {

statement(s);

} while (conditional expression);

As you can see in the syntax description, the statements execute

before a conditional expression is evaluated. Unlike the simpler while

statement, the statements in a do . . . while statement always execute

once before a conditional expression is evaluated.

The following do . . . while statement executes once before the con-

ditional expression evaluates the count variable. Therefore, a single

line that reads “The count is equal to 2” appears. After the conditional

expression ($Count < 2) executes, the $Count variable is equal to 2.

This causes the conditional expression to return a value of FALSE, and

the do . . . while statement ends.

$Count = 2;

do {

echo "<p>The count is equal to $Count</p>";

++$Count;

} while ($Count < 2);

101

Note that the preceding example includes a counter within the body

of the do . . . while statement. As with the while statement, you need

to include code that changes the conditional expression to prevent an

infinite loop.

In the following example, the while statement never executes

because the count variable does not fall within the range of the con-

ditional expression:

$Count = 2;

while ($Count < 2) {

echo "<p>The count is equal to $Count</p>";

++$Count;

}

The following script shows an example of a do . . . while statement

that displays the days of the week, using an array:

$DaysOfWeek = array("Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday", "Sunday");

$Count = 0;

do {

echo $DaysOfWeek[$Count], "<br />";

++$Count;

} while ($Count < 7);

In the preceding example, an array is created containing the days of

the week. A variable named $Count is declared and initialized to zero.

(Remember, the first subscript or index in an array is zero.) Therefore,

in the example, the statement $DaysOfWeek[0]; refers to Monday.

The first iteration of the do . . . while statement displays “Monday”


CHAPTER 2

Functions and Control Structures

102

and then increments the count variable by 1. The conditional expres-

sion in the while statement then checks to determine when the last

element of the array has been displayed. As long as the count is less

than seven (which is one number higher than the index of the largest

element in the $DaysOfWeek[] array), the loop continues. Figure 2-9

shows the output of the script in a Web browser.

Figure 2-9

Output of days of week script in a Web browser

Next, you will replace the while statement in the DiceRoll.php script

with a do . . . while statement. Because the two types of statements

are so similar, there is little benefit in replacing the while statement.

You will add a do . . . while statement to the script for practice.

To use a do . . . while statement:

1.

2.

Return to the DiceRoll.php document in your text editor.

Change the while statement to a do . . . while statement, as

follows:

do {

$Dice[0] = rand(1,6);

$Dice[1] = rand(1,6);

$Score = $Dice[0] + $Dice[1];

echo "<p>";

echo "The total score for roll $RollNumber was

$Score.<br />";

$Doubles = CheckForDoubles($Dice[0],$Dice[1]);

DisplayScoreText($Score, $Doubles);

echo "</p>";

if ($Doubles)

++$DoublesCount;

++$RollNumber;

} while ($RollNumber <= 5); /* End of the do . . .

while loop */


Repeating Code

3.

4.

Save and upload the DiceRoll.php document.

Open the DiceRoll.php file in your Web browser by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.02/Chapter/DiceRoll.php. The output should still

appear as shown in Figure 2-8.

Close your Web browser window.

103

5.

for Statements

So far, you have learned how to use the while and the do . . . while

statements to repeat, or loop through, code. You can also use the

for statement to loop through code. Specifically, the for statement

is used for repeating a statement or series of statements as long as a

given conditional expression evaluates to TRUE. The for statement

performs essentially the same function as the while statement: if a

conditional expression within the for statement evaluates to TRUE,

the for statement executes and continues to execute repeatedly until

the conditional expression evaluates to FALSE.

A primary difference between while and for statements is that,

in addition to a conditional expression, the for statement can also

include code that initializes a counter and changes its value with each

iteration. This is useful because it provides a specific place for you to

declare and initialize a counter, and to update its value, which helps

prevent infinite loops. The syntax of the for statement is as follows:

for (counter declaration and initialization; condition;

update statement) {

statement(s);

}

When the PHP interpreter encounters a for loop, the following steps

occur:

1.

The counter variable is declared and initialized. For example,

if the initialization expression in a for loop is $Count = 1;,

a variable named $Count is declared and assigned an initial

value of 1. The initialization expression is only started once,

when the for loop is first encountered.

The for loop condition is evaluated.

If the condition evaluation in Step 2 returns a value of TRUE,

the for loop statements execute, Step 4 occurs, and the pro-

cess starts over again with Step 2. If the condition evaluation

in Step 2 returns a value of FALSE, the for statement ends and

the next statement following the for statement executes.

2.

3.


CHAPTER 2

You can omit

any of the

three parts of

the for state-

ment, but you

must include the semico-

lons that separate each

section. If you omit a

section, be sure you

include code within the

body that will end the

for statement, or your

program might get

caught in an infinite loop.

Functions and Control Structures

4.

The update statement in the for statement is executed. For

example, the $Count variable may increment by 1.

The following script shows a for statement that displays the contents

of an array:

$FastFoods = array("pizza", "burgers", "french fries",

"tacos", "fried chicken");

for ($Count = 0; $Count < 5; ++$Count) {

echo $FastFoods[$Count], "<br />";

}

104

As you can see in this example, the counter is initialized, evaluated,

and incremented within the parentheses. You do not need to include

a declaration for the $Count variable before the for statement, nor do

you need to increment the $Count variable within the body of the for

statement. Figure 2-10 shows the output of the fast foods script.

Figure 2-10

Output of the fast foods script

Using a for statement is more efficient because you do not need as

many lines of code. Consider the following while statement:

$Count = 1;

while ($Count <= 5) {

echo "$Count<br />";

++$Count;

}

You could achieve the same flow control more efficiently by using a

for statement as follows:

for ($Count = 1; $Count <= 5; ++$Count) {

echo "$Count<br />";

}

The following code shows an example of the “days of the week”

script you saw earlier. This time, however, the script includes a


Repeating Code

for statement instead of a do . . . while statement. Notice that the

declaration of the $Count variable, the conditional expression, and

the statement that increments the $Count variable are now all con-

tained within the for statement. Using a for statement instead of a

do . . . while statement simplifies the script somewhat because you

do not need as many lines of code.

$DaysOfWeek = array("Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday", "Sunday");

for ($Count = 0; $Count < 7; ++$Count) {

echo $DaysOfWeek[$Count], "<br />";

}

105

To replace the do . . . while statement in DiceRoll.php with a for

statement:

1.

2.

Return to the DiceRoll.php document in your text editor.

Change the do . . . while statement to a for statement, as

follows:

for ($RollNumber = 1; $RollNumber <= 5;

++$RollNumber) {

$Dice[0] = rand(1,6);

$Dice[1] = rand(1,6);

$Score = $Dice[0] + $Dice[1];

echo "<p>";

echo "The total score for roll $RollNumber was

$Score.<br />";

$Doubles = CheckForDoubles($Dice[0],$Dice[1]);

DisplayScoreText($Score, $Doubles);

echo "</p>";

if ($Doubles)

++$DoublesCount;

} // End of the for loop

3.

4.

Save and upload the DiceRoll.php document.

Open the DiceRoll.php file in your Web browser by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.02/Chapter/DiceRoll.php. The output should still

appear as shown in Figure 2-8.

Close your Web browser window.

5.

foreach Statements

The foreach statement is used to iterate or loop through the ele-

ments in an array. With each loop, a foreach statement moves to the

next element in an array. Unlike other types of looping statements,

you do not need to include any sort of counter within a foreach

statement. Instead, you specify an array expression within a set of


CHAPTER 2

Functions and Control Structures

parentheses following the foreach keyword. The basic syntax for the

foreach statement is as follows:

foreach ($array_name as $variable_name) {

statement(s);

}

106

During each iteration, a foreach statement assigns the value of the

current array element to the $variable_name argument specified in

the array expression. You use the $variable_name argument to access

the value of the element that is available in an iteration. For example,

the following code declares the same $DaysOfWeek[] array you’ve

seen a few times in this chapter. During each iteration, the expression

in the foreach statement assigns the value of each array element to

the $Day variable. An echo statement within the foreach statement’s

braces displays the value of the current element.

You will

receive an

error if you

attempt to

use a

foreach statement with

any variable types other

than arrays.

$DaysOfWeek = array("Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday", "Sunday");

foreach ($DaysOfWeek as $Day) {

echo "<p>$Day</p>";

}

The foreach statement in the preceding code simply displays the days

of the week to the Web browser.

The more advanced form of the foreach statement allows you to

retrieve both the index (or key) and the value of each array element.

foreach ($array_name as $index_name => $variable_name) {

statement(s);

}

This form of the foreach statement works almost exactly the same

as the basic form. The only difference is that the index of the current

array element is stored in the $index_name variable. For example, the

following code declares the $DaysOfWeek[] array again. During each

iteration, the expression in the foreach statement assigns the index

value of each array element to the $DayNumber variable and the value

of each array element to the $Day variable. An echo statement within

the foreach statement’s braces displays the index and value of the

current element. Figure 2-11 shows the output of this version.

$DaysOfWeek = array("Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday", "Sunday");

foreach ($DaysOfWeek as $DayNumber => $Day) {

echo "<p>Day $DayNumber is $Day</p>";

}


Repeating Code

107

Figure 2-11

Output of the foreach script with index values

To create a final version of DiceRoll.php that displays all possible out-

comes of rolling two dice:

1.

2.

Return to the DiceRoll.php document in your text editor.

Immediately after the declaration of the $FaceNamesSingular

and $FaceNamesPlural arrays, declare a new array named

$FaceValues, as follows:

$FaceValues = array( 1, 2, 3, 4, 5, 6);

3.

Delete the declaration of the $Dice array and add a new dec-

laration for a variable named $RollCount, as follows:

$RollCount = 0;

4.

Create a new array called $ScoreCount and initialize it using

the following for loop:

$ScoreCount = array();

for ($PossibleRolls = 2; $PossibleRolls <= 12;

++$PossibleRolls) {

$ScoreCount[$PossibleRolls] = 0;

}


CHAPTER 2

Functions and Control Structures

5.

Replace the for statement with the following two nested

foreach statements:

foreach ($FaceValues as $Die1) {

foreach ($FaceValues as $Die2) {

6.

108

Delete the two calls to rand(1,6) and the $Score variable

assignment, and insert the following lines in their place:

++$RollCount;

$Score = $Die1 + $Die2;

++$ScoreCount[$Score];

7.

Modify the call to the CheckForDoubles() function to use

$Die1 and $Die2 instead of $Die[0] and $Die[1].

$Doubles = CheckForDoubles($Die1,$Die2);

8.

Replace the single closing brace for the for loop with two

closing braces for the two foreach loops:

} // End of the foreach loop for $Die2

} // End of the foreach loop for $Die1

9.

Modify the echo statement that displays the doubles count

with an echo statement that displays the doubles count and

the roll count.

echo "<p>Doubles occurred on $DoublesCount of the

$RollCount rolls.</p>";

10. Finally, add a foreach loop to display the number of times

each score occurred. Use the second form of the foreach

statement to get the array index, which is the score.

foreach ($ScoreCount as $ScoreValue => $ScoreCount) {

echo "<p>A combined value of $ScoreValue

occurred $ScoreCount of $RollCount

times.</p>";

}

11. Save and upload the DiceRoll.php document.

12. Open the DiceRoll.php file in your Web browser by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.02/Chapter/DiceRoll.php. The output should appear

as shown in Figure 2-12.


Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]