So far we have learned about the following control structures:

  1. if, elseif, else
  2. while
  3. for

But there are still more. We'll first look at the switch construct.

Switch

The syntax for a switch statement looks something like this:

switch (expression) {
    case value1:
        //some code
    case value2:
        //some code
    case value3:
        //some code
    default:
        //some code
}

When this code is executed, each case is looked at in order. If(value1 == expression), then all code under that case and the code under all subsequent cases will be executed. If not, it will check if(value2 == expressions) and so on. If none of the cases match, the default case is used. You can have as many or as few cases as you want, and having the default case is optional. An important thing that is often forgotten is that all code underneath a true case is executed, even the code within the following cases.

$n = 3;
switch($n){
    case 0:
        print "$n is equal to 0\n";
    case 1:
        print "$n is less than or equal to 1\n";
    case 2:
        print "$n is less than or equal to 2\n";
    case 3:
        print "$n is less than or equal to 3.\n";
    case 4:
        print "$n is less than or equal to 4.\n";
    case 5:
        print "$n is less than or equal to 5.\n";
}

When the above code is executed, the following will be printed:

3 is less than or equal to 3.
3 is less than or equal to 4.
3 is less than or equal to 5.

Notice that once an appropriate case is found, all code in the following cases is executed as well. There is a way to prevent this though. Using the break; command you can jump to the closing brace of the switch statement preventing any more code from being executed.

Also, a default case will be used when no other cases match.

switch ($n) {
    case 0:
        print "$n is zero.";
        break;
    case 1:
    case 4:
    case 9:
        print "$n is a perfect square.";
        break;  
    case 2:
        print "$n is an even number.";
    case 3:
    case 5:
    case 7:
        print "$n is a prime number.";
        break;
    case 6:
    case 8:
        print "$n is an even number.";
        break;
    default:
        print "Only single-digit numbers are allowed.";
        break;
}

Test for Understanding

  1. What will print if $n is set to 7?
  2. What will print if $n is set to 1?
  3. What will print if $n is set to 20?

Answers:

  1. 7 is a prime number.
  2. 1 is a perfect square.
  3. Only single-digit numbers are allowed.
Be Sociable, Share!