PHP Flow Control and Looping

From Techotopia
Revision as of 15:48, 31 May 2007 by Neil (Talk | contribs) (JavaScript Conditional Statements)

Jump to: navigation, search

One of the main reasons for using scripting languages such as PHP is to build logic and intelligence into the creation and deployments of web based data. In ordedr to be able to build logic into PHP it necessary for the script to be able to make decisions and repeast tasks based on specified criteria.

For example it may be necessary to repeat a section of a script a specified number of times, or perform a task only if one or more conditions are found to be true (i.e only let the user log in if a valid passowrd has been provided).

In programming terms this is known as flow control and looping. In the simplest terms this involves some standard scripting structures provided by languages such as PHP to control the logic and overal behavior of a script. Each of these structures provides a simple and intuitive way to build intelligence into scripts. These PHP structures can be broken down into a number of categories as follows:

Conditional Statements

  • if statements
  • if ... else ... statements

Looping Statements

  • while loops
  • do ... while loops

switch Statements

label Statements

with Statements

In this chapter we will explore each of these categories in turn and create some examples that demsonstrate how to implement these mechanisms.


Contents


PHP Conditional Statements

Just about everything in life revolves around decisions. We wouldn't get very far through the day if we weren't able to decide what to wear, what to eat and which way to drive to work. Similarly computers would be of little use without some innate ability to evaluate choices and decisions. If all we were able to do was provide as computer with a set of instructions that simply followed one after the other with no ability to make choices based on specific criteria, none of the software we have today would exist.

Conditional statements provide the core of building decision making into scripting langauges such as PHP. Conditional statements essentially control whether a part of a script is executed depending the result of a particular expression (i.e whether an expression returns a boolean true or false value). The two types of conditional structures provided by PHP (and most other programming langauges) are if and if ... else. In this section we will take a close look at each of these condtional structures, and also provide some examples of their use.

The PHP if Statement

The first line of an if statement involves the if statement followed by the expression to be evaluated in parentheses. For example:

if (i < 2)

In the above example if i is less than 2 then the expression will be evaluated as being true, otherwise it will be returned as false

The next step in constructing an if statement is to specify what action should be taken if the expression is true. This is acheived by placing the lines of script to be executed in open and closing braces after the if statement:

if (i < 2)
{
      document.writeln ("The value of i is less than 2");
      i++;
}

Note that if there is only one line of script to be performed if the if expression is true then the braces are optional:

if (i < 2)
      document.writeln ("The value of i is less than 2");

Whilst this is perfectly valid JavaScript it is recommended, for the purposes of consistent scripting style, that the braces be used even for a single line of script after the 'if' statement.


The JavaScript if ... else Statements

The if statement above allows you to specify what should happen if a particular expression evaluates to true. It does not, however, provide the option to specify something else that should happen in the event that the expression evaluates to be false. This is where the if ... else construct comes into play.

The syntax for if ... else is the same as for the if statement with the exception that the else statement can be used to specify alternate action:

if (customerName = "Fred")
{
      document.write ("Hello Fred!");
} 
else 
{
      document.write ("You're not Fred! Where's Fred?");
}

As shown in the above example the script following the if statement is executed when the expression is evaluated to be true (i.e the customerName variable contains the string "Fred") and the script after the else statement is executed when the customerName does not match the string "Fred".

if ... else structures can be taken a step further to implement if ... else ... if structures. For example:


if (customerName = "Fred")
{
      document.write ("Hello Fred!");
} 
else if (customerName = "John")
{
      document.write ("Hello John!");
} 
else
{
      document.write ("You're not Fred! Where's Fred?");
}

JavaScript Looping Statements

It is generally common knowledge that computers are great at performing repetitive tasks an infinite number of times, and doing so very quickly. It is also common knowlede that computers really don't do anything unless someone programs them to tell them what to do. Loop statements are the primary mechanism for telling a computer to perform the same task over and over again until a set of crieria are met. This is where for, while and do ... while loops are of use.

JavaScript for loops

Suppose you wanted to add a number to itself ten times. One way to do this might be to write the following JavaScript:


var j = 10;

j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;

Whilst this is somewhat cumbersome it does work. What would happen, however, if you needed to perform this task 100 times or 10,000 times. Writing a script to perform this as above would be prohibitive. This is exactly what the for loop is intended to handle.

The syntax of a for loop is as follows:

for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
      statements to be executed
}

The initializer typically initializes a counter variable. Traditionally the variable i is used for this purpose. For example:

i = 0

which sets the counter to be the value i and sets it to zero.

The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of times. For example, if we want to loop 100 times:

i < 10

Finally the loop expression specifies the action to perform on the counter variable. For example to increment by 1:

i++

Bringing this all together we can create a for loop to perform the task outlined in the earlier example:


var j = 10;

for (i=0; i<10; i++)
{
      j += j;
}

As with the if statement, the enclosing braces are optional if a single line of script is to be executed, but their use is recommended regardless.

JavaScript while loops

The for loop described above works well when you know how many times a particular task needs to be repeated. Clearly there will often be instances where something needs to be repeated until a certain condition is met, with no way of knowing how many repetitions are going to be needed to meet that criteria. To address this need JavaScript provides the while loop. In essense the while loop repeats a set of tasks until a specified condition is met. The while loop syntax is as follows:

while (''condition'')
{
      ''JavaScript Statements''
}

where condition is an expression that will return either true or false and JavaScript Statements represents the JavaScript to be executed while the expression is true. For example:

while ( i < 10 )
{
      i = i + j;
}

In the above example the while expression will evaluate whether i is less than 10. If it is already greater than 10 then the code in the braces is skipped and the loop exits without performing any tasks. If it is not greater than 10 the code in the braces is executed and the loop returns to while statement and repeats the evaluation of i. This process repeats until i is greater than 10, at which point the loop exits.

JavaScript do ... while loops

Think of the do ... while loop as an inverted while loop. As shown above, the while loop evaluates an expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check then the code is not executed. The do .. while loop is provided for situations where you know that the code in your loop will always need to be executed at least once. For example you may want to keep asking a user to fill in a field in a prompt dialog until specific text is entered. You know that you have to show the prompt dialog at least once to get a string from the user to evaluate against. The syntax for the do ... while loop is as follows:

do
{
       ''JavaScript statement''
} while (''conditional expression'')

In the do ... while example below a prompt dialog will be displayed and the user response assigned to a variable. Until that variable matches the name "John" the loop will continue to display the prompt dialog to the user:


do
{
        var userResponse;
        userResponse = prompt ("Enter your name", "");
} while (userResponse != "John")

JavaScript switch Statements

if ... else constructs work fine if you need to check a value against criteria (for example checking the value of a string against a couple of possible candidates as follows:

if (customerName = "Fred")
{
      document.write ("Hello Fred!");
} 
else if (customerName = "John")
{
      document.write ("Hello John!");
} 
else
{
      document.write ("You're not Fred! Where's Fred?");
}

This can become cumbersome, however, when a need arises to evaluate a large number of conditions. An easier way to handle such situations is to use the switch statement, the syntax for which is as follows:

switch (''value'')
{
     case "''match1''" :
     ''statements''
     break;

     case "''match2''" :
     ''statements''
     break;

     case "''match3''" :
     ''statements''
     break;

     case "''match4''" :
     ''statements''
     break;

     case "''match5''" :
     ''statements''
     break;

     default :
     ''statements''
     break;
}

There can be any number of case statements - basically as many as you need to fully compare the value in the switch statement against the possible options (represented by match1 through to match5 in the above example) specified by the case statements. When a match is found the statements corresponding to the matching case are executed. Note the break; statement. Without the break all the cases after the matching case will also be executed.

The default statement specifies the action that should be taken if no match is found. The following provides an example of the switch statement in action:


var carModel = "Focus";

switch (carModel)
{
     case "Durango" :
     document.write ("Manufactured by Dodge");
     break;

     case "Camry" :
     document.write ("Manufactured by Toyota");
     break;

     case "Focus" :
     document.write ("Manufactured by Ford");
     break;

     case "320i" :
     document.write ("Manufactured by BMW");
     break;

     case "Civic" :
     document.write ("Manufactured by Honda");
     break;

     default  :
     document.write ("Unknown Car Model");
     break;
}

Breaking a Loop

Occasionally it is necessary to exit from a loop before it has met whatever completion criteria were specified. To achieve this, the break statement must be used. The following example contains a loop that uses the break statement to exit from the loop when i = 100, even though the loop is designed to iterate 1000 times:


for (i = 0; i < 1000; i++)
{
        if (i == 10) 
        {
             break;
        }
}

label Statements

One problem that can arise using the break statement involves breaking from a loop that is nested inside another loop. In the following example the break will break out of the inner loop, but not the outer loop:


for (i = 0; i < 1000; i++)
{
     for (x = 0; x < 100; x++)
     {
        if (x == 10) 
        {
             break;
        }
     }
)

In the above example the break will break out of the inner loop when x is equal to 10 but the outer for loop will continue to run. This is fine if that is the desired behavior, but is a problem if the outer loop needs to also be broken at this point. This problem can be resolved using label statements. label statements are placed before the control structure and referenced in the break statement to instruct the loop to break out of all layers of nesting in the loop:

loopExit:
for (i = 0; i < 1000; i++)
{
     for (x = 0; x < 100; x++)
     {
        if (x == 10) 
        {
             break loopExit;
        }
     }
)

Skipping Statements in Current Loop Iteration

The break statement, when encountered in a loop breaks skips all remaining statements in the loop body and breaks the loop. The continue statement also skips all remaining statements in the loop for the current interation, but returns to the top of the loop and allows it to continue running.