• No results found

Flow Control Statements

In document 01_PHP_Rev1_4_IG (Page 70-78)

PHP F OUNDATIONS

3 PHP F OUNDATIONS .1 Learning Objectives

3.6 Flow Control Statements

Flow control statements, or instructions, when executed redirect the normal sequence of the original program execution, or the execution logic. When discussing flow control, the reference is to a single thread of execution which is dependent upon instructions that are executed one at a time. Within PHP, two categories of flow control statements can be identified:

• Conditional – these statements alter the normal sequence of the original program execution based on the value of an expression. These expressions can be any expression that is usable within MySQL stored routines and return a value. In MySQL, conditional flow control statements are represented in the if and switch statements.

• Iterative - these statements provide for the repeated processing of commands based on a condition that must be met. The most common reason to use iterative statements or instructions within a LAMP architecture is to process all the returned rows of a MySQL SELECT statement. Other reasons for an iterative flow control statement to be setup in PHP include:

o Executing more complex mathematical algorithms

o Processing an external file by looping through each record in that file

In PHP these are represented in the while, do...while, for and foreach statements.

47

3.6.1 if ... else ... elseif

In most programming languages, including PHP, the if statement is the most basic of all choice flow controls or conditional constructs. The syntax resembles that which is listed below:

if (test_condition1) {

... -- statements that execute if test_condition1 is True } else if (test_condition2) {

... -- statements that execute if test_condition2 is True } else {

... -- statements that execute if all preceding test_conditions are False or Unknown }

The minimum that is required for an if statement to be valid is if (test_condition) { ... }.

However, a test_condition can result in three different returned values:

o True - the statements enclosed within an if condition (or else if) will be executed when the expression results in a true condition. In the case of a numeric value expression (or a value that PHP perceives as numeric), the statement is considered true if the returned results is an absolute value of 1 or greater (this would include positive and negative values).

o False - when an expression results in a false condition, the statement enclosed is bypassed. A false condition in a numeric value expression (or a value that PHP perceives as numeric) when the returned result is zero (0).

o Unknown - when an expression can not be evaluated to either a true or false condition, SQL returns an unknown (or null) condition. Most errors in stored routines stem from not developing guards to manage null conditions. The following example demonstrates a common error that can result in misleading and inaccurate results:

<?php

$currentDate = time();

if (strtotime($_POST['DateEntered']) > $currentDate) { echo 'That date is in the future';

} elseif (strtotime($_POST['DateEntered']) < $currentDate) { echo 'That date is in the past';

} else {

echo 'That is today';

}

?>

In the event that the date is equivalent to today's date or if the date entered can not be evaluated (an unknown condition), the response will be the same 'That is today'. This of course is not an accurate statement and would result in an inaccurate response to the purpose of this date check.

48

Due to an expression having the ability to return any of these three results (True, False or Unknown), it is crucial to ensure that your coding reflect each of these possibilities. In addition, to addressing this three-valued logic in your if statements (and other flow control statements), there are a number of ways to actually format your statements. The following are all equivalent to each other and will be read by PHP identically:

<?php

$currentDate = time();

if (strtotime($_POST['DateEntered']) > $currentDate) { echo 'That date is in the future';

} elseif (strtotime($_POST['DateEntered']) < $currentDate) { echo 'That date is in the past';

} else {

echo 'That is today';

}

?>

<?php

$currentDate = time();

if (strtotime($_POST['DateEntered']) > $currentDate) {

echo 'That date is in the future';

}

else if (strtotime($_POST['DateEntered']) < $currentDate) {

echo 'That date is in the past';

} else {

echo 'That is today';

}

?>

Coding Preference

As seen here, PHP is very flexible in the format in which the code is actually entered. Any combination of formats can be utilized; however, the most important thing to remember is consistency and a format that works best not only for yourselves but also for others who may have to review the code in the future. Formatting can be a small issue that presents large problems if not discussed and formalized from the very beginning of a project.

Instructor Note: As stated earlier, the if and switch statements are very similar in their capabilities, readability and logic, so when is one better than the other. This question can be best addressed by personal preference;

however, there are some fundamental issues that may make the decision more straightforward than that:

- Familiarity - if is a more familiar construct for most programmers and it ability to evaluate multiple expressions based on multiple variables tends to be easier to follow and understand.

- Readability - switch is slightly more readable when a single expression is being evaluated against a range of values that are static and well-defined.

- Consistency - the advantages that one has over the other is minimal and the big question is going to be which 3.6.2 Switch

The switch statement provides a means of developing complex conditional constructs. The switch choice works on the principle of comparing a given value with specified constants and acting upon the first constant that is matched. If the constants form a compact range then this can be implemented very efficiently as if it were a choice based on whole numbers.

switch(variable) {

The switch statement is grouped with the if statement based on its logic and the similarities between the two choices. Anything that a switch statement can do, an if statement can also do and vice-versa. In either case, when a condition is found to be TRUE all other choices are ignored (if properly coded with break statements). This can lead to some very interesting coding issues and requires the programmer to see through the process to decipher the error. The following is an example of using the switch statement:

<?php

3.6.3 While

The while function is the simplest of all the iterative control statements. The statement list within a while statement is repeated as long as the condition evaluated has not been met. The statement list within the while code body can consist of one or more statements.

while (expression) {

-- statements that execute while the expression evaluates false

}

It is a best practice to build error detecting logic into any iterative control statement. This error control logic should be built in such a way as to detect an infinite loop. In the following example, simple logic has been built into a while function to detect an infinite loop error:

<?php

The do ... while function is based on the while iterative control statement with the difference being the condition is evaluated at the end of the statement execution versus at the beginning. The statement list within a do ... while function is repeated as long as the condition evaluated has not been met. The statement list within the do ... while code body can consist of one or more statements.

do {

-- statements that execute while the expression evaluates false and then it iterates through the statements one more time } while (expression);

A do ... while statement will always be guaranteed to run through the statements contained at least once. The following example demonstrates how a do ... while statement works:

<?php

/* The number 100 will be displayed, even though 10 is not less than 5. If this was a while statement, the statements would not have run at all */

?>

50

51

Instructor Notes: The code $ctemp = $ctemp + 1 could of course be written shorter by just using $ctemp++;

however, there are many reasons to not encourage shortcuts like this and encourage more control over the expected results (rather than trusting PHP to handle that control).

3.6.5 For

The for function is the more complex sibling of the while function and provides a more streamline and complex looping mechanism. The for function takes three expressions; the first expression is evaluated by default at the first iteration of the loop, the second expression is evaluated at the beginning of each iteration (and determines if the loop will continue) and the third expression is evaluated at the conclusion of each loop. Any of the expressions can be empty and the logic that would take place in the expression can be substituted in the body of the function itself. The statement list within the for code body can consist of one or more statements.

for (expression1; expression2; expression3) {

-- statements that execute while the expressions evaluates false }

The following examples demonstrate how the for iterative control statement can work:

<?php

for ($ctemp = 0; $ctemp <= 20; $ctemp = $ctemp + 1) { $ftemp = 32 + $ctemp / 5 * 9;

echo "$ctemp -> $ftemp<br>";

}

?>

<?php

for ($ctemp = 0; ; $ctemp = $ctemp + 1) { $ftemp = 32 + $ctemp / 5 * 9;

echo "$ctemp -> $ftemp<br>";

if ($ctemp >= 20) break;

}

?>

<?php

$ctemp = 0;

for (;;) {

$ftemp = 32 + $ctemp / 5 * 9;

echo "$ctemp -> $ftemp<br>";

if ($ctemp >= 20) break;

$ctemp = $ctemp + 1;

}

?>

52

3.6.6 Foreach

The foreach function is the iterative control statement that is designed specifically for handling arrays (and objects as of PHP 5). There are two ways of using the foreach iterative control statement. The first ways is by looping over the array given by the array_expression and assigning the current array element to the $value variable.

foreach (array_expression as $value) {

-- statements that execute until the array reaches the end or a manual break is inserted

}

The second way of using the foreach function is similar to the first, except the element value is assigned to a $key variable.

foreach (array_expression as $key => $value) {

-- statements that execute until the array reaches the end or a manual break is inserted

}

Each time the foreach command is initiated, the internal pointer to the array is reset and each iteration advances the pointer one element. The following examples demonstrate how the foreach iterative control statement can work:

<?php

$last_name = array("Smith", "Jones", "Sanchez", "Green");

foreach ($last_name as $individual) {

echo "The average temperature for the week was $wk_avg";

?>

53

3.6.6.1 Break and Continue

With iterative control statements, PHP provides two means of manually interrupting the flow of the loops.

These two commands include break (which has already been used in examples up to this point) and continue. The following example demonstrates how these two loop interrupts can be used in iterative control statements:

<?php

for ($test=1; $test < 10; $test = $test + 1) { if ($test==3) continue;

if ($test==6) break;

echo "The test number is $test<br>";

}

?>

The following output would be displayed when this PHP script was run:

The test number is 1 The test number is 2 The test number is 4 The test number is 5

When the $test variable was equal to 3, the script skipped the remain code and performed the next iteration of the for function. This resulted in the number 3 not being printed. In addition, when the $test variable was equal to 6, the break function ended the for function thus resulting in the remainder of the script being missed resulting in the number 6 not being printed.

54

In document 01_PHP_Rev1_4_IG (Page 70-78)