3.3. The switch Statement

An alternative to if-elseif-else structures is the switch statement, which works on the assumption that you compare a single expression to a set of possible values. Figure 3.3 demonstrates the structure of a switch statement.

Figure 3.3. The switch statement.
						switch(root-expression)
						{
						case case-expression:
    default:
						}
					

The root expression inside a switch statement is evaluated and then compared to each expression following a case statement. At the end of the list of cases you can put a default statement that works exactly like an else statement; it matches if no other case matches.

Notice that cases don't have curly braces after them. This reveals an important difference between if and switch. When an if block matches ...

Get Core PHP Programming, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.