PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


Control Structures Revisited
Pages: 1, 2

A new look at the 'while' statement

Now that we have covered both elseif and the conditonal assignment operator, we'll quickly take a look at a different flavor of the while statement: the do...while(). The do...while statement is nearly identical in syntax and behavior to a standard while statement with to differences. The first difference is in its syntax, the second is its functionality. The syntax for a do...while statement is:



do {
  ...
} while(<condition);

The real use (and difference) in a do...while statement as opposed to a standard while statement is how many times the code contained within it is guaranteed to execute. In a standard while statement, in theory the code contained within it could never be executed (the conditions required was never achieved). In a do while, the code contained within it will execute at least once (or more depending again on the conditions of the while). Below is an example of using a do...while statement to generate a random number greater than 100:

<?php
  do {
    $myval = rand()
    } while($myval < 100);
?>

The result will be a value $myval that will always be above 100.

The 'switch' control structure

To wrap up our continued discussion of control structures, we'll introduce a very useful alternative to use the if statement: the switch statement. switch statements are unique to any other control structure we have seen thus far, but in essence provide the same functionality as a conditional if statement. For example: Let's assume you would like to develop a script that would process commands from a menu. For argument's sake we'll assume the following menu items:

Home
Links
E-mail Us

In order to make development easier, we'll also assign special one-word identification codes to each of the three menu items. We'll call these home, links, and email respectively.

Now that we have our menu options, and the identification codes assigned to each of them, it is time to write the logic that will determine which option the user selected. When the user clicks on one of our options, we'll send to PHP a variable $menu containing the identification string. So, all we have to do now is check the value of $menu to determine what option the user clicked on. There are a few methods a developer can use to accomplish such a task, such as the use of if...elseif, in code such a method would resemble the following:

<?php
  if($menu == "home") {
    echo "You clicked home";

  } elseif($menu == "links") {

    echo "You clicked links";
  } elseif($menu == "email") {
    echo "You clicked e-mail";
  } else {
    echo "I don't know what you clicked";
  }
?>

Unfortunately, code such as this tends to get confusing and out of hand rather quickly. It is for circumstances such as this that the switch statement was developed.

How the 'switch' statement works

The switch statement could be visually represented as a dial with a number of positions on it. These positions are called "cases." When this imaginary dial is "switched" to one of the positions, a particular piece of code is executed that is associated with that dial. With that in mind, let's examine the syntax of a switch statement:

Switch(<variable>) {
  [case <constant value>:]
  [case <constant value>:]
  ...
  [default:]
}

Looking at the above switch syntax we can see that the statement itself is variable and then within the code block is contained any number of case statements (each requiring a constant value) followed by an optional default case. So how does it work? When a switch statement is executed, it takes the variable passed to it (such as our $menu) and the compares it against each of the case statement values.

In the event that the case statement value matches the value of the variable, the code below the case statement is executed. Optionally, you can also provide a default case to be executed in the event that none of the defined cases matches the provided variable. But, before we can continue and look at it in action we need to introduce a special companion statement to the switch control structure: the break statement.

Using the 'break' statement

When a switch statement matches a particular case, as we stated before, the code directly below it is executed. However, PHP will not stop executing code inside of a switch when it encounters another case statement. Rather, it will ignore all further case statements and execute all of the code below the original match. For example:

<?php
  $menu = "links";
  switch($home) {
    case "home":
      echo "You clicked home";
    case "links":
      echo "You clicked links";
    case "email":
      echo "You clicked e-mail";
    default:
      echo "I don't know what you clicked";
  }
?>

When the above code is executed, instead of the output simply being:

You clicked links

It will output:

You clicked links
You clicked e-mail
I don't know what you clicked

Although the break statement is most commonly found within a switch statement, it can be used in any code block to cancel execution of any further code within that block. Therefore it can be used to escape out of for loops, while loops, or even if statements.

Because PHP was not told to stop executing the code, it continued straight through the entire switch statement and disregarded all further cases. Also note that PHP did not execute the "home" case since it was before the matching case "links." Sometimes, such behavior is beneficial, but in a scenario such as ours we would like to know exactly which case was selected and what menu option was clicked. By using the break statement we can command PHP to stop executing the code and leave the command block as demonstrated below:

<?php
  $menu = "links";
  switch($home) {
    case "home":
      echo "You clicked home";
      break;
    case "links":
      echo "You clicked links";
      break;
    case "email":
      echo "You clicked e-mail";
      break;
   default:
      echo "I don't know what you clicked";
      break;
  }
?>

With the use of the break statement, PHP will only execute the code between the different cases and our output will be as expected.

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.


Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: