Control Structures


PHP comes with a rich set of flow-of-control operators, which evaluate expressions and take appropriate action based on the result.

if Statements

 if (expr)   block1 else block2 

The most basic control structure is the if statement. An expression is evaluated, and if the result is TRUE, then the first block of code is executed. Otherwise, an optional second block of code (demarcated by the else keyword) is executed. The blocks of code are either a single statement terminated by a semicolon (;) or a sequence of statements enclosed in brackets. Multiple if statements can be chained together by replacing the else keyword with elseif.

 <?php   if ($a == 1)   {     echo "A is 1!!!!";   }   else if ($a == 2)                // you can do this or ...     echo "A is 2 ...";   elseif ($a == 3)                 // you can do this.   {     echo "A is three.  Odd!";   }   else   {     echo "A is some other value.";   } ?> 

It should be noted that elseif and else if are functionally equivalentthey end up resulting in the same code path execution. However, for those paying extremely close attention, the difference between them lies strictly in how the language engine parses and sees them internally.

switch Statement

 switch (expr1) {   case expr2:       block1   case expr3:       block2   ...   case exprn:       blockn   default:      endblock } 

There are times when we want to compare an expression value or variable value against a number of possibilities. This can be done with a long series of if statements, but this ends up looking unattractive. To help with this, the switch statement is provided. The switch statement executes an initial expression (expr1) and then compares its value against the values of the expressions associated with the individual case statements.

For the first that matches, it begins executing the code associated with that case statement. It then continues executing all statements it sees and ignores any further case statements until the end of the switch statement. To have it stop executing statements before then, the break, continue, or return keyword needs to be inserted (the first two of which tell it to stop executing; we will see more about the return keyword in Chapter 3). If none of the case statements matches, PHP looks for a default statement and executes code there. If none is found, no code is executed.

Unlike some other languages, PHP is not restricted to integer/scalar values in the case labels. Full expressions, variables, and strings can be included in these.

 <?php   switch ($user_name)   {     case "Administrator":       $allow_access_to_admin_pages = TRUE;       echo "Administrator Logging in ...";       break;     case "Visitor":                // fall through     case "Guest":     case "Temporary":       $allow_access_to_admin_pages = FALSE;       echo "Guest User Login";       continue;                         // same as 'break'     case "SuperBadUser":       $allow_access_to_admin_pages = FALSE;       echo "Banned User SuperBadUser attempted login!";       break;     case $temporary_administrator:       $allow_access_to_admin_Pages = TRUE;       echo "Temporary Administrator Logging In";       // oops.  Forgot the "break" -- will continue executing       // lines of code ...  this is a bug!     default:       // regular user  no special access.       $allow_access_to_admin_pages = FALSE;       echo "User $user_name logging in.";       break;   }   switch ($number)   {     case $current_hour:       echo "The number is the same as the current hour!";       break;     case $user_age * 10:       echo "The number is the same as the user's age times 10";       break;     default:       echo "It's a number";       break;   } ?> 

while/do…while Loops

 while (expr)    block do   block while (expr); 

Beyond the decision making shown thus far comes the need to repeat the same section of code multiple times, which is commonly known as looping. The while and do…while loops are the most basic of these loops. In both constructs, the code inside the block is executed as long as the expression associated with the while keyword evaluates to trUE. The difference between the two loops is that in the case of the simple while loop, the expression is evaluated before the code in the block executes, whereas in the do…while loop, it is evaluated after the code block is executed.

 <?php   $a = 0;   while ($a < 10)   {     echo "\$a is going up: $a<br/>";     $a++;   }   do   {     echo "\$a is going down: $a<br/>";     $a--;   }   while ($a > 0); ?> 

When you write loops, you should be careful to avoid writing infinite loopsloops in which the conditional expression always evaluates to trUE.

 $x = 0; while ($x < 10) {   echo $x . "<br/>\n";   // whoops -- forgot $x++ here !!! } 

The previous loop will never evaluate to FALSE since $x will always have the value 0. Eventually, PHP will simply terminate our script by saying it has run for too long.

for Loops

 for (expr1; expr2; expr3)   block 

Another useful looping construct is the for loop, where three expressions are presented. The order of evaluation is as follows:

  • expr1 This is evaluated (executed really, since the result is ignored) once, when the for loop is first encountered. Once this is done, loop iteration begins.

  • expr2 This is evaluated before each iteration. If it evaluates to TRUE, then the block of code is executed.

  • expr3 This is evaluated (executed) after each iteration, again with the result ignored.

  • expr2 Iteration begins anew.

 <?php   for ($a = 0; $a < 10; $a++)   {     echo "\$a is now: $a<br/>";   } ?> 

foreach Loops

Another looping structure is the foreach loop, which is restricted to certain types. We will cover this in more detail in Chapter 5.

Interrupting Loops

There are times when writing a loop where you would you get "out of" the loop and stop iterating. There are also times when you would like to skip over the rest of the code in the loop and restart the evaluation test and iteration.

Both of these tasks can be accomplished with judicious placement of if statements and variables to help the expression determine when to get out of the loop. There are also two keywords in PHP to make the task a bit easierbreak and continue.

break tells PHP to abort execution of the current loop and continue past the end. (Please note that if the loop is nested within another loop, the outer loop continues executing.) To have it break out of the outer loop, an integer argument can be specified, telling PHP how many nested loops to break out of. If it is not specified, this argument defaults to 1.

continue tells PHP to skip the execution of the rest of the code for the current loop and proceed directly to the expression evaluation to determine whether to iterate again. Like the break keyword, you can also specify an integer argument after the continue keyword, which tells PHP to step out of the current loop and count that many loops up (including the current one) before continuing. If it is not specified, this argument also defaults to 1.

 <?php   $a = 0;   while ($a < 1000)   {     $a++;     echo "\$a is now: $a<br/>";     //     // localtime() returns an array.  The hour is      // in key/index 2, 24hr format.     //     $now = localtime();     if ($now[2] > 17)     {       // union Rules: no working past 5pm       break;     }   }   //   // print out only odd numbers.   //   for ($b = 0; $b < 1000; $b++)   {     if ($b % 2 == 0)       continue;     echo "\$b is now: $b<br/>";   }   for ($x = 0; $x < 10; $x++)   {     echo $x;     for ($y = 15; $y < 20; $y++)     {       // this tells PHP to exit this loop and        // continue the outer loop!       if ($y == 17)         continue 2;       echo $y;     }   } ?> 




Core Web Application Development With PHP And MYSQL
Core Web Application Development with PHP and MySQL
ISBN: 0131867164
EAN: 2147483647
Year: 2005
Pages: 255

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net