Make your own free website on Tripod.com

Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

The switch Decision Structure

The swich construct is one more of those constructs that we use to "decide" what to do depending on the prevalent conditions. Unfortunately, switch ONLY tests a set of expressions that return integer values.

The syntax for the switch construct is:

switch(test expression){
	case: int1
		PHP statement 1;
		PHP statement 2;
		PHP statement 3;
		break;

	case: int2
		PHP statement 1;
		PHP statement 2;
		PHP statement 3;
		break;

	default:
		PHP statement 1;
		PHP statement 2;
		PHP statement 3;
		break;
}

What the heck is this supposed to mean? I'll tell ya'

We said that the switch construct is ideal for those test expressions that return an integer. In our syntax block, the returned integers are int1 and int2.

For each of the possible occurences, we add statements to be executed and MUST also add a break after each case otherwise all the expressions will be executed - ignoring the switch as if it did not exist.

Let's take an example. In this code fragment, we will create routine to produce a remark based on a grade. In our grading system, grades 1 and 2 should yield the remark "poor", grades 3 and 4 "fair", 5 is "good", 6 to 8 "very good" and 9 and 10 "excellent":

switch($grade){
	
	case 1:
	case 2:
	   $remark = "poor";
	   break;

	case 3:
	case 4:
	   $remark = "fair";
	   break;

	case 5:
	   $remark = "good";
	   break;

	case 6:
	case 7:
	case 8:
	   $remark = "very good";
	   break;

	case 9:0
	case 10:
	   $remark = "excellent";
	   break;
	}

Of course. Let's analyze our code. Let's start half-way. Look at the line for case 5. The code execution will get here if the supplied test expression ($grade in this case) is 5. When and if it is equal to 5, the variable remark will be assigned the value "good" and the program will break;

What this means is that the break; will force the code to stop bothering about the other cases and proceed on with the rest of the program (ie. the next line of code after the closing curly bracket.

Back to the op. Let's look at case 1. It doesn't have a break. What this means is that should the state expression ($grade) be 1, the code will not do anything but since there is no break, it will go on to case 2 in which case the $remark variable is assigned the value "poor" before breaking from the structure.

Mmmm... Not as bad as you thought is it?

<< The if... elseif Control Structure | Repetition(Iteration) Constructs >>

JamHitz Productions