PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

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.


As you work with these statements, what are you learning and how are you applying it?
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • um...isn't this code wrong....
    2002-08-28 12:51:40  minkqulax [Reply | View]

    Here is your code from the example with the "break" statement

    <?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;
    }
    ?>


    That will always produce "I don't know what you clicked" because you set the switch at $home and there is no $home. If you set the switch to $menu...it will work as expected.


Tagged Articles

Be the first to post this article to del.icio.us

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com