the switch statementtmyn1 the switch statement sometimes there can be a multiple-choice situation,...

Post on 24-Dec-2015

213 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

The switch Statement tMyn 1

The switch Statement

• Sometimes there can be a multiple-choice situation, in which you need to execute a particular set of statements from a number of choices depending on the value of an integer variable or expression.

• The statement that will handle precisely this sort of situation is called the switch statement.

• The choices are called cases.

The switch Statement tMyn 2

• The selection between a number of cases is determined by the value of an integer expression that you specify between parentheses following the keyword switch.

• The case values appear in a case label:

case caseValue:

• The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings.

The switch Statement tMyn 3

• The default label identifies the default case, which is a catch-all; the statements that follow are executed if the selection expression does not correspond to any of the case values.

• The break statement that appears after each set of case statements is absolutely necessary for the logic here.

The switch Statement tMyn 4

The switch Statement tMyn 5

The switch Statement tMyn 6

The switch Statement tMyn 7

• It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

The switch Statement tMyn 8

The switch Statement tMyn 9

The switch Statement tMyn 10

The switch Statement tMyn 11

• The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

The switch Statement tMyn 12

The switch Statement tMyn 13

top related