Flow Control Functions in PHP - PHP Language Structure - Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Part II. PHP Language Structure

Chapter 6. Flow Control Functions in PHP


In this chapter, you learn the following:

How to use the if statement to execute code if a test expression evaluates to true

How to execute alternative blocks of code when the test expression of an if statement evaluates to false

How to use the switch statement to execute code based on the value returned by a test expression

How to repeat execution of code using a while statement

How to use for statements to make neater loops

How to break out of loops

How to nest one loop within another

How to use PHP start and end tags within control structures


The scripts created in the previous chapter flow only in a single direction: forward. That is, the same statements execute in the same order every time a script is run. This does not allow for much flexibility because any sort of dynamic programming must, at the very least, have a loop or two, not to mention the ability to check for the validity of certain conditions before proceeding onward. You now learn about the programming structures that enable your scripts to adapt to circumstances.

Switching Flow

It is common for scripts to evaluate conditions and change their behavior accordingly. These decisions are what make your PHP pages dynamic—that is, able to change output according to circumstances. Like most programming languages, PHP enables you to do this with an if statement.

The if Statement

The if statement is a way of controlling the execution of a statement that follows it (that is, a single statement or a block of code inside braces). The if statement evaluates an expression found between parentheses. If this expression results in a true value, the statement is executed. Otherwise, the statement is skipped entirely. This functionality enables scripts to make decisions based on any number of factors:

if (expression) {
// code to execute if the expression evaluates to true
}

Listing 6.1 executes a block of code only if a variable contains the string "happy".

Listing 6.1 An if Statement


1: <?php
2: $mood = "happy";
3: if ($mood == "happy") {
4: echo "Hooray! I'm in a good mood!";
5: }
6: ?>


In line 2, the value "happy" is assigned to the variable $mood. In line 3, the comparison operator == compares the value of the variable $mood with the string "happy". If they match, the expression evaluates to true, and the subsequent code is executed until the closing bracket is found (in this case, in line 5).

Put these lines into a text file called testif.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

Hooray! I'm in a good mood!

If you change the assigned value of $mood to "sad" or any other string besides "happy", and then run the script again, the expression in the if statement evaluates to false, and the code block is skipped. The script remains silent, which leads to the else clause.

Using the else Clause with the if Statement

When working with an if statement, you might want to define an alternative block of code that should be executed if the expression you are testing evaluates to false. You can do this by adding else to the if statement followed by a further block of code:

if (expression) {
// code to execute if the expression evaluates to true
} else {
// code to execute in all other cases
}

Listing 6.2 amends the example in Listing 6.1 so that a default block of code is executed if the value of $mood is not equivalent to "happy".

Listing 6.2 An if Statement That Uses else


1: <?php
2: $mood = "sad";
3: if ($mood == "happy") {
4: echo "Hooray! I'm in a good mood!";
5: } else {
6: echo "I'm in a $mood mood.";
7: }
8: ?>


Put these lines into a text file called testifelse.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

I'm in a sad mood.

Notice in line 2 that the value of $mood is the string "sad", which obviously is not equal to "happy", so the expression in the if statement in line 3 evaluates to false. This results in the first block of code (line 4) being skipped. However, the block of code after else is executed, and the alternate message is printed: I'm in a sad mood. The string "sad" is the value assigned to the variable $mood.

Using an else clause in conjunction with an if statement allows scripts to make decisions about code execution. However, your options are limited to an either-or branch: either the code block following the if statement or the code block following the else statement. You’ll now learn about additional options for the evaluation of multiple expressions, one after another.

Using the elseif Clause with the if Statement

You can use an if...elseif...else clause to test multiple expressions (the if...else portion) before offering a default block of code (the elseif portion):

if (expression) {
// code to execute if the expression evaluates to true
} elseif (another expression) {
// code to execute if the previous expression failed
// and this one evaluates to true
} else {
// code to execute in all other cases
}

If the initial if expression does not evaluate to true, the first block of code is ignored. The elseif clause presents another expression for evaluation. If it evaluates to true, its corresponding block of code is executed. Otherwise, the block of code associated with the else clause is executed. You can include as many elseif clauses as you want; and if you don’t need a default action, you can omit the else clause.


Note

The elseif clause can also be written as two words (else if). The syntax you use is a matter of taste, but coding standards employed by PEAR (the PHP Extension and Application Repository) and PECL (the PHP Extension Community Library) use elseif.


Listing 6.3 adds an elseif clause to the previous example.

Listing 6.3 An if Statement That Uses else and elseif


1: <?php
2: $mood = "sad";
3: if ($mood == "happy") {
4: echo "Hooray! I'm in a good mood!";
5: } elseif ($mood == "sad") {
6: echo "Awww. Don't be down!";
7: } else {
8: echo "I'm neither happy nor sad, but $mood.";
9: }
10: ?>


Once again, the $mood variable has a value of "sad", as shown in line 2. This value is not equal to "happy", so the code in line 4 is ignored. The elseif clause in line 5 tests for equivalence between the value of $mood and the value "sad", which in this case evaluates to true. The code in line 6 is therefore executed. In lines 7 through 9, a default behavior is provided, which would be invoked if the previous test conditions were all false. In that case, we would simply print a message including the actual value of the $mood variable.

Put these lines into a text file called testifelseif.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

Awww. Don't be down!

Change the value of $mood to "iffy" and run the script. It produces the following output:

I'm neither happy nor sad, but iffy.

The switch Statement

The switch statement is an alternative way of changing flow, based on the evaluation of an expression. Using the if statement in conjunction with elseif, you can evaluate multiple expressions, as you’ve just seen. However, a switch statement evaluates only one expression in a list of expressions, selecting the correct one based on a specific bit of matching code. Whereas the result of an expression evaluated as part of an if statement is interpreted as either true or false, the expression portion of a switch statement is subsequently tested against any number of values, in hopes of finding a match:

switch (expression) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}

The expression used in a switch statement is often just a variable, such as $mood. Within the switch statement, you find a number of case statements. Each of these cases tests a value against the value of the switch expression. If the case value is equivalent to the expression value, the code within the case statement is executed. The break statement ends the execution of the switch statement altogether.

If the break statement is omitted, the next case statement is executed, regardless of whether a previous match has been found. If the optional default statement is reached without a previous matching value having been found, its code is executed.


Caution

It is important to include a break statement at the end of any code that will be executed as part of a case statement. Without a break statement, the program flow continues to the next case statement and ultimately to the default statement. In most cases, this results in unexpected behavior, likely incorrect!


Listing 6.4 re-creates the functionality of the if statement example using the switch statement.

Listing 6.4 A switch Statement


1: <?php
2: $mood = "sad";
3: switch ($mood) {
4: case "happy":
5: echo "Hooray! I'm in a good mood!";
6: break;
7: case "sad":
8: echo "Awww. Don't be down!";
9: break;
10: default:
11: echo "I'm neither happy nor sad, but $mood.";
12: break;
13: }
14: ?>


Once again, in line 2 the $mood variable is initialized with a value of "sad". The switch statement in line 3 uses this variable as its expression. The first case statement in line 4 tests for equivalence between "happy" and the value of $mood. There is no match in this case, so script execution moves on to the second case statement in line 7. The string "sad" is equivalent to the value of $mood, so this block of code is executed. The break statement in line 9 ends the process. Lines 10 through 12 provide the default action, should neither of the previous cases evaluate as true.

Put these lines into a text file called testswitch.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

Awww. Don't be down!

Change the value of $mood to "happy" and run the script. It produces the following output:

Hooray! I'm in a good mood!

To emphasize the caution about the importance of the break statement, try running this script without the second break statement. Be sure to change the value of $mood back to "sad" and then run the script. Your output will be as follows:

Awww. Don't be down!I'm neither happy nor sad, but sad.

This is definitely not the desired output, so be sure to include break statements where appropriate.

Using the ?: Operator

The ?: or ternary operator is similar to the if statement, except that it returns a value derived from one of two expressions separated by a colon. This construct provides you with three parts of the whole, hence the name ternary. The expression used to generate the returned value depends on the result of a test expression:

(expression) ? returned_if_expression_is_true : returned_if_expression_is_false;

If the test expression evaluates to true, the result of the second expression is returned; otherwise, the value of the third expression is returned. Listing 6.5 uses the ternary operator to set the value of a variable according to the value of $mood.

Listing 6.5 Using the ?: Operator


1: <?php
2: $mood = "sad";
3: $text = ($mood == "happy") ? "I am in a good mood!" : "I am in a $mood
mood.";
4: echo "$text";
5: ?>


In line 2, $mood is set to "sad". In line 3, $mood is tested for equivalence to the string "happy". Because this test returns false, the result of the third of the three expressions is returned.

Put these lines into a text file called testtern.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

I am in a sad mood.

The ternary operator can be difficult to read, but is useful if you are dealing with only two alternatives and want to write compact code.

Loops

So far, you’ve looked at decisions that a script can make about what code to execute. Scripts can also decide how many times to execute a block of code. Loop statements are specifically designed to enable you to perform repetitive tasks because they continue to operate until a specified condition is achieved or until you explicitly choose to exit the loop.

The while Statement

The while statement looks similar in structure to a basic if statement, but has the ability to loop:

while (expression) {
// do something
}

Unlike an if statement, a while statement executes for as long as the expression evaluates to true, over and over again if need be. Each execution of a code block within a loop is called an iteration. Within the block, you usually change something that affects the while statement’s expression; otherwise, your loop continues indefinitely. For example, you might use a variable to count the number of iterations and act accordingly. Listing 6.6 creates a while loop that calculates and prints multiples of 2 up to 24.

Listing 6.6 A while Statement


1: <?php
2: $counter = 1;
3: while ($counter <= 12) {
4: echo $counter." times 2 is ".($counter * 2)."<br />";
5: $counter++;
6: }
7: ?>


This example initializes the variable $counter in line 2 with a value of 1. The while statement in line 3 tests the $counter variable so that as long as the value of $counter is less than or equal to 12, the loop continues to run. Within the while statement’s code block, the value of $counter is multiplied by 2, and the result is printed to the browser. In line 5, the value of $counter is incremented by 1. This step is extremely important because if you did not increment the value of the $counter variable, the while expression would never resolve to false and the loop would never end.

Put these lines into a text file called testwhile.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
4 times 2 is 8
5 times 2 is 10
6 times 2 is 12
7 times 2 is 14
8 times 2 is 16
9 times 2 is 18
10 times 2 is 20
11 times 2 is 22
12 times 2 is 24

The do...while Statement

A do...while statement looks a little like a while statement turned on its head. The essential difference between the two is that the code block is executed before the truth test and not after it:

do {
// code to be executed
} while (expression);


Caution

The test expression of a do...while statement should always end with a semicolon.


This type of statement is useful when you want the code block to be executed at least once, even if the while expression evaluates to false. Listing 6.7 creates a do...while statement. The code block is executed a minimum of one time.

Listing 6.7 The do...while Statement


1: <?php
2: $num = 1;
3: do {
4: echo "The number is: ".$num."<br />";
5: $num++;
6: } while (($num > 200) && ($num < 400));
7: ?>


The do...while statement tests whether the variable $num contains a value that is greater than 200 and less than 400. Line 2 initializes $num to 1, so this expression returns false. Nonetheless, the code block is executed at least one time before the expression is evaluated, so the statement prints a single line to the browser.

Put these lines into a text file called testdowhile.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

The number is: 1

If you change the value of $num in line 2 to 300 and then run the script, the loop displays

The number is: 300

and continues to print similar lines, with increasing numbers, through

The number is: 399

The for Statement

Anything you want to do with a for statement can also be done with a while statement, but a for statement is often a more efficient method of achieving the same effect. In Listing 6.6, you saw how a variable was initialized outside the while statement and then tested within its expression and incremented within the code block. With a for statement, you can achieve this same series of events, but in a single line of code. This allows for more compact code and makes it less likely that you might forget to increment a counter variable, thereby creating an infinite loop:

for (initialization expression; test expression; modification expression) {
// code to be executed
}


Note

Infinite loops are, as the name suggests, loops that run without bounds. If your loop is running infinitely, your script is running for an infinite amount of time. This behavior is very stressful on your web server and renders the web page unusable.


The expressions within the parentheses of the for statement are separated by semicolons. Usually, the first expression initializes a counter variable, the second expression is the test condition for the loop, and the third expression increments the counter. Listing 6.8 shows a for statement that re-creates the example in Listing 6.6, which multiplies 12 numbers by 2.

Listing 6.8 Using the for Statement


1: <?php
2: for ($counter=1; $counter<=12; $counter++) {
3: echo $counter." times 2 is ".($counter * 2)."<br />";
4: }
5: ?>


Put these lines into a text file called testfor.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
4 times 2 is 8
5 times 2 is 10
6 times 2 is 12
7 times 2 is 14
8 times 2 is 16
9 times 2 is 18
10 times 2 is 20
11 times 2 is 22
12 times 2 is 24

The results of Listings 6.6 and 6.8 are the same, but the for statement makes the code in Listing 6.8 more compact. Because the $counter variable is initialized and incremented at the beginning of the statement, the logic of the loop is clear at a glance. That is, as shown in line 2, the first expression initializes the $counter variable and assigns a value of 1, the test expression verifies that $counter contains a value that is less than or equal to 12, and the final expression increments the $counter variable. Each of these items is found in the single line of code.

When the sequence of script execution reaches the for loop, the $counter variable is initialized and the test expression is evaluated. If the expression evaluates to true, the code block is executed. The $counter variable is then incremented and the test expression is evaluated again. This process continues until the test expression evaluates to false.

Breaking Out of Loops with the break Statement

Both while and for statements incorporate a built-in test expression with which you can end a loop. However, the break statement enables you to break out of a loop based on the results of additional tests. This can provide a safeguard against error. Listing 6.9 creates a simple for statement that divides a large number by a variable that is incremented, printing the result to the screen.

Listing 6.9 A for Loop That Divides 4000 by 10 Incremental Numbers


1: <?php
2: for ($counter=1; $counter <= 10; $counter++) {
3: $temp = 4000/$counter;
4: echo "4000 divided by ".$counter." is...".$temp."<br />";
5: }
6: ?>


In line 2, this example initializes the variable $counter and assigns a value of 1. The test expression in the for statement verifies that the value of $counter is less than or equal to 10. Within the code block, 4000 is divided by $counter, printing the result to the browser.

Put these lines into a text file called testfor2.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

4000 divided by 1 is... 4000
4000 divided by 2 is... 2000
4000 divided by 3 is... 1333.33333333
4000 divided by 4 is... 1000
4000 divided by 5 is... 800
4000 divided by 6 is... 666.666666667
4000 divided by 7 is... 571.428571429
4000 divided by 8 is... 500
4000 divided by 9 is... 444.444444444
4000 divided by 10 is... 400

This seems straightforward enough. But what if the value you place in $counter comes from user input? The value could be a negative number or even a string. Let’s take the first instance, where the user input value is a negative number. Changing the initial value of $counter from 1 to -4causes 4000 to be divided by 0 when the code block is executed for the fifth time. It is generally not a good idea for your code to divide by 0 because such an operation results in an answer of “undefined.” Listing 6.10 guards against this occurrence by breaking out of the loop if the value of the $counter variable equals 0.

Listing 6.10 Using the break Statement


1: <?php
2: $counter = -4;
3: for (; $counter <= 10; $counter++) {
4: if ($counter == 0) {
5: break;
6: } else {
7: $temp = 4000/$counter;
8: echo "4000 divided by ".$counter." is...".$temp."<br />";
9: }
10: }
11 ?>



Note

Dividing a number by 0 does not cause a fatal error in PHP. Instead, PHP generates a warning and execution continues.


Listing 6.10 uses an if statement, shown in line 4, to test the value of $counter before attempting mathematical operations using this value. If the value of $counter is equal to 0, the break statement immediately halts execution of the code block, and program flow continues after the forstatement (line 11).

Put these lines into a text file called testfor3.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

4000 divided by -4 is... -1000
4000 divided by -3 is... -1333.33333333
4000 divided by -2 is... -2000
4000 divided by -1 is... -4000

Notice that the $counter variable was initialized in line 2, outside the for statement’s parentheses. This method was used to simulate a situation in which the value of $counter is set from outside the script.


Tip

You can omit any of the expressions from a for statement, but you must remember to retain the separation semicolons.


Skipping an Iteration with the continue Statement

The continue statement ends execution of the current iteration but doesn’t cause the loop as a whole to end. Instead, the next iteration begins immediately. Using the break statement as in Listing 6.10 is a little drastic. With the continue statement in Listing 6.11, you can avoid a divide-by-0 error without ending the loop completely.

Listing 6.11 Using the continue Statement


1: <?php
2: $counter = -4;
3: for (; $counter <= 10; $counter++) {
4: if ($counter == 0) {
5: continue;
6: }
7: $temp = 4000/$counter;
8: echo "4000 divided by ".$counter." is...".$temp."<br />";
9: }
10: ?>


Line 5 swaps the break statement for a continue statement. If the value of the $counter variable is equivalent to 0, the iteration is skipped, and the next one starts immediately.

Put these lines into a text file called testcontinue.php and place this file in your web server document root. When you access this script through your web browser, it produces the following output:

4000 divided by -4 is... -1000
4000 divided by -3 is... -1333.33333333
4000 divided by -2 is... -2000
4000 divided by -1 is... -4000
4000 divided by 1 is... 4000
4000 divided by 2 is... 2000
4000 divided by 3 is... 1333.33333333
4000 divided by 4 is... 1000
4000 divided by 5 is... 800
4000 divided by 6 is... 666.666666667
4000 divided by 7 is... 571.428571429
4000 divided by 8 is... 500
4000 divided by 9 is... 444.44444444444
4000 divided by 10 is... 400


Caution

Using the break and continue statements can make code more difficult to read because they often add layers of complexity to the logic of the loop statements that contain them. Use these statements with care, or comment your code to show other programmers (or yourself) exactly what you’re trying to achieve with these statements.


Nesting Loops

Loops can contain other loop statements, as long as the logic is valid and the loops are tidy. The combination of such statements proves particularly useful when working with dynamically created HTML tables. Listing 6.12 uses two for statements to print a multiplication table to the browser.

Listing 6.12 Nesting Two for Loops


1: <?php
2: echo "<table style=\"border: 1px solid #000;\"> \n";
3: for ($y=1; $y<=12; $y++) {
4: echo "<tr> \n";
5: for ($x=1; $x<=12; $x++) {
6: echo "<td style=\"border: 1px solid #000; width: 25px;
7: text-align:center;\">";
8: echo ($x * $y);
9: echo "</td> \n";
10: }
11: echo "</tr> \n";
12: }
13: echo "</table>";
14: ?>


Before you examine the for loops, take a closer look at line 2 in Listing 6.12:

echo "<table style=\"border: 1px solid black;\"> \n";

Notice that Listing 6.12 uses the backslash character (\) before each of the quotation marks within the string containing the style information for the table. These backslashes also appear in lines 6 and 7, in the style information for the table data cell. This is necessary because it tells the PHP engine that we want to use the quotation mark character, rather than have PHP interpret it as the beginning or end of a string. If you did not “escape” the quotation marks with the backslash character, the statement would not make sense to the engine; it would read it as a string followed by a number followed by another string. Such a construct would generate an error. This line also uses \n to represent a newline character, which makes the source easier to read when it is rendered by the browser, which is useful especially when looking at HTML for tables.

The outer for statement (line 3) initializes a variable called $y, assigning to it a starting value of 1. This for statement defines an expression that intends to verify that the value of $y is less than or equal to 12, and then defines the increment that will be used. In each iteration, the code block prints a tr (table row) HTML element (line 4) and begins another for statement (line 5). This inner loop initializes a variable called $x and defines expressions along the same lines as for the outer loop. For each iteration, the inner loop prints a td (table cell) element to the browser (lines 6 and 7), as well as the result of $x multiplied by $y (line 8). Line 9 closes the table cell. After the inner loop has finished, execution falls back through to the outer loop, where the table row closes on line 11, ready for the process to begin again. When the outer loop has finished, the result is a neatly formatted multiplication table. Listing 6.12 wraps things up by closing the table on line 13.

Put these lines into a text file called testnestfor.php and place this file in your web server document root. When you access this script through your web browser, it should look like Figure 6.1.

image

Figure 6.1 Output of testnestfor.php.

Code Blocks and Browser Output

In Chapter 4, “Installing and Configuring PHP,” you learned that you can slip in and out of HTML mode at will using the PHP start and end tags. In this chapter, you have discovered that you can present distinct output to the user according to a decision-making process you can control withif and switch statements. This section combines these two techniques.

Imagine a script that outputs a table of values only when a variable is set to the Boolean value true. Listing 6.13 shows a simplified HTML table constructed with the code block of an if statement.

Listing 6.13 A Code Block Containing Multiple echo Statements


1: <?php
2: $display_prices = true;
3: if ($display_prices) {
4: echo "<table border=\"1\">\n";
5: echo "<tr><td colspan=\"3\">";
6: echo "today's prices in dollars";
7: echo "</td></tr>";
8: echo "<tr><td>\$14.00</td><td>\$32.00</td><td>\$71.00</td></tr>\n";
9: echo "</table>";
10: }
11: ?>



Caution

In line 8, note the dollar sign, which when meant literally and not as part of a variable declaration, must be escaped with a backslash for it to be interpreted as the dollar sign character.


If the value of $display_prices is set to true in line 2, the table is printed. For the sake of readability, we split the output into multiple echo() statements, and once again use the backslash to escape any quotation marks used in the HTML output.

Put these lines into a text file called testmultiecho.php and place this file in your web server document root. When you access this script through your web browser, it should look like Figure 6.2.

image

Figure 6.2 Output of testmultiecho.php.

There’s nothing wrong with the way this is coded, but you can save yourself some typing by simply slipping back into HTML mode within the code block. Listing 6.14 does just that.

Listing 6.14 Returning to HTML Mode Within a Code Block


1: <?php
2: $display_prices = true;
3: if ($display_prices) {
4: ?>
5: <table border="1">
6: <tr><td colspan="3">today's prices in dollars</td></tr>
7: <tr><td>$14.00</td><td>$32.00</td><td>$71.00</td></tr>
8: </table>
9: <?php
10: }
11: ?>


The important thing to note here is that the shift to HTML mode on line 4 occurs only if the condition of the if statement is fulfilled. This can save you the bother of escaping quotation marks and wrapping our output in echo() statements. This approach might, however, affect the readability of the code in the long run, especially if the script grows larger.

Summary

In this chapter, you learned about control structures and the ways in which they can help to make your scripts flexible and dynamic. Most of these structures reappear regularly throughout the rest of the book.

You learned how to define an if statement and how to provide for alternative actions with the elseif and else clauses. You learned how to use the switch statement to change flow according to multiple equivalence tests on the result of an expression. You learned about loops—in particular, the while and for statements—and you learned how to use break and continue to prematurely end the execution of a loop or to skip an iteration. You learned how to nest one loop within another and saw a typical use for this structure. You also looked at a technique for using PHP start and end tags in conjunction with conditional code blocks, to alleviate having to escape (use the backslash in front of) special characters such as the quotation mark and dollar sign.

You should now know enough of the basics to write scripts of your own that make decisions and perform repetitive tasks. In the next chapter, you learn how to add even more power to your applications. You learn how functions enable you to organize your code, preventing duplication and improving reusability.

Q&A

Q. Must a control structure’s test expression result in a Boolean value?

A. Ultimately, yes. But in the context of a test expression, 0, an undefined variable, or an empty string is converted to false. All other values evaluate to true.

Q. Must I always surround a code block in a control statement with brackets?

A. If the code you want executed as part of a control structure consists of only a single line, you can omit the brackets. However, the habit of always using opening and closing brackets, regardless of structure length, is a good one.

Workshop

The workshop is designed to help you review what you’ve learned and begin putting your knowledge into practice.

Quiz

1. How do you use an if statement to print the string "Youth message" to the browser if an integer variable, $age, is between 18 and 35? If $age contains any other value, the string "Generic message" should be printed to the browser.

2. How do you extend your code in question 1 to print the string "Child message" if the $age variable is between 1 and 17?

3. How do you create a while statement that increments through and prints every odd number between 1 and 49?

4. How do you convert the while statement you created in question 3 into a for statement?

Answers

1.

$age = 22;

if (($age >= 18) && ($age <= 35)) {
echo "Youth message";
} else {
echo "Generic message";
}

2.

$age = 12;

if (($age >= 18) && ($age <= 35)) {
echo "Youth message";
} elseif (($age >= 1) && ($age <= 17)) {
echo "Child message";
} else {
echo "Generic message";
}

3.

$num = 1;

while ($num <= 49) {
echo $num."<br />";
$num += 2;
}

4.

for ($num = 1; $num <= 49; $num += 2) {
echo $num."<br />";
}

Activities

1. Review the syntax for control structures. Think about how the techniques you’ve learned will help you in your scripting. Perhaps some of the script ideas you develop will be able to behave in different ways according to user input or will loop to display an HTML table.

2. Start to build the control structures you will be using. Use temporary variables to mimic user input or database queries for the time being.